Skip to content

Instantly share code, notes, and snippets.

@raftheunis87
Created October 8, 2019 04:37
Show Gist options
  • Save raftheunis87/2ede0e20209e9f32fd01a4a52f278bac to your computer and use it in GitHub Desktop.
Save raftheunis87/2ede0e20209e9f32fd01a4a52f278bac to your computer and use it in GitHub Desktop.
contact_form.php
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
empty($_POST['response']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Log
$log = "--------------------------------------------------".PHP_EOL.
"user: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
"name: ".$name.PHP_EOL.
"email_address: ".$email_address.PHP_EOL.
"message: ".$message.PHP_EOL;
file_put_contents('./log_'.date("Y.n.j").'.txt', $log, FILE_APPEND);
// RECAPTCHA VARS
$secret = "<recaptcha_secret_goes_here>";
$response = $_POST['response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip";
$captcha_response = file_get_contents($url);
if($captcha_response['success'] == true) {
$log = "bot: no".PHP_EOL.
"--------------------------------------------------".PHP_EOL;
file_put_contents('./log_'.date("Y.n.j").'.txt', $log, FILE_APPEND);
// Create the email and send the message
$to = '<your_email_address>';
$email_subject = "My website contact form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n\n$message";
$headers = "From: noreply@<my_company>.be\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
} else {
$log = "bot: yes".PHP_EOL.
"--------------------------------------------------".PHP_EOL;
file_put_contents('./log_'.date("Y.n.j").'.txt', $log, FILE_APPEND);
echo "Captcha not validated by Google!";
return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment