Skip to content

Instantly share code, notes, and snippets.

@galileoguzman
Created February 9, 2018 19:03
Show Gist options
  • Save galileoguzman/757f5fd151987a9ed8a971cdc24e513d to your computer and use it in GitHub Desktop.
Save galileoguzman/757f5fd151987a9ed8a971cdc24e513d to your computer and use it in GitHub Desktop.
For little problems fix 'em with little solutions. We were in a project where we just had apache and php installed and we needed save emails from a form with ajax.
<?php
function saveEmail($email){
$file = 'emails.txt';
return file_put_contents($file, PHP_EOL.$email, FILE_APPEND | LOCK_EX);
}
function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function sendJSONResponse($message, $error){
$data = array(
'message' => $message,
'error' => $error
);
header('Content-type: application/json');
echo json_encode( $data );
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['goodfetch_email'])){
if(validateEmail($_POST['goodfetch_email'])){
if (saveEmail($_POST['goodfetch_email'])) {
sendJSONResponse('Email saved successfully!', false);
}else{
sendJSONResponse('One monkey stole our database, but some of our engineers are about to reach it, try later please.! XD', true);
}
}else{
sendJSONResponse('Email validation faild.', true);
}
}else{
sendJSONResponse('You have to send an email.', true);
}
}else{
header('Location: http://goodfetch.com');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment