This is some code snippets, to add a php mail form, with reCAPTCHA to your site.
Get your reCAPTCHA keys here: https://www.google.com/recaptcha
mail.php
<?php
if(isset($_POST['usermail'])){
$userIP = $_SERVER["REMOTE_ADDR"];
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = "recaptcha secret key";
$request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
if(strstr($request, "true")){
$usermail = $_POST['usermail'];
$username = $_POST['username'];
$userphone = $_POST['userphone'];
$message = "New user:\r\n Name: " . $username . "\r\n Mail: " . $usermail . "\r\n Phone: " . $userphone;
$to = 'lasse@lasse-it.dk';
$from = 'php@lasse-it.dk';
$subject = 'New user';
$headers = 'From:' . $from . "\r\n" .
'Reply-To: ' . $from . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
}
header ( "Location: /" );
die ();
?>
mail.html
<head> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <form action="mail.php" method="post"> Full name:<br> <input type="text" name="username"> <br> Email:<br> <input type="text" name="usermail"> <br><br> Phone:<br> <input type="text" name="userphone"> <input type="submit" value="Submit"> <div class="g-recaptcha" data-sitekey=""></div> </form> </body>






One thought on “A simple PHP mail form with reCAPTCHA”
I’m a dummy with php, so I hope my question doesn’t sound too stupid ;-(
I’ve created a html and a php file, I’ve copied/pasted the codes and entered the secret key (and adapted the e-mail address). But…it says unvalid site key/ the recaptcha doesn’t work. What did I do wrong; how can I improve it? Thanks in advance for your reaction!
Truus de Vries