A friend of mine asked me for a quick and simple way to add ReCaptcha to a contact form on her site. For demonstration purposes, I created a form from scratch and tossed ReCaptcha's PHP API onto it. Check out the example below. This is a very very basic contact form with simple field validation and an html-based email that is sent out.

Just Updated!

Well hello there - I've recently upgraded this after some feedback:

  • I have clarified on what my sanitization does.
  • Added new mail() headers to allow the receiver to respond right to whoever sent the email
  • Moved our error display to be inside the form, so we can place our operating code elsewhere.
  • Placed our form inside of an HTML5 document frame
  • Added a basic CSS rule to make our error text red

The Code

Last Updated: 8/26/2012
Author: Max Morgan
URL: http://maxmorgandesign.com/php_recaptcha/
Latest Code: http://playground.maxmorgandesign.com/recaptcha/form.txt
Support: phprecaptcha@maxmorgandesign.com
//Make sure you put your keys here
$publickey = 'YOUR KEY HERE-';
$privatekey = ' YOUR KEY HERE';
$toEmail = 'phprecaptcha@maxmorgandesign.com';
include 'recaptchalib.php';
//If somebody has posted data, we run verification
if ( isset($_POST['FirstName']) ) { 
PHP will generally add stripslashes to all posted data. This removes it and helps to sanitize data for security reasons.
trim() - Removes whitespace from the ends of a string. "  hello! " => "hello!"
stripslashes - Reverses addslashes() that most servers apply to POST data by default "max's test" => "max's test"
htmlentities - Converts special characters to their counterpart - "<script>" => "&lt;script&gt;"
foreach ( $_POST as $k => $v ) $_POST[$k] = htmlentities(stripslashes(trim($v)),ENT_QUOTES);
//Basic Validation. We are storing errors in an arrray.
if ( empty($_POST['FirstName']) ) $errors[] = 'Please enter your first name!';
if ( empty($_POST['LastName']) ) $errors[] = 'Please enter your last name!';
if ( empty($_POST['Email']) ) $errors[] = 'Please enter your email address!';
if ( empty($_POST['Comments']) ) $errors[] = 'Please enter your comments!';
//Captcha Validation
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
if ( $resp->error=='incorrect-captcha-sol' ) $errors[] = 'The captcha you filled out did not match the image. Please try again.';
else $errors[] = $resp->error;
//We check to see if we have any errors. If not, send the email
if ( !isset($errors) ) {
/* Our message - you can change this up and use full HTML here! */
$message = '<p><b>First Name: </b>'.$_POST['FirstName'].'</p>';
$message .= '<p><b>Last Name: </b>'.$_POST['LastName'].'</p>';
$message .= '<p><b>Email: </b>'.$_POST['Email'].'</p>';
$message .= '<p><b>Comments: </b><br/>'.$_POST['Comments'].'</p>';
/* Mail headers */
//This form sent the email - so let the receiver know
$headers =   'From: Your Website <phprecaptcha@maxmorgandesign.com> ' . "rn" .
//Allows us to set a default "Reply-To" - Hitting "Reply" will make your email go to whoever filled out the form.
'Reply-To: '.$_POST['FirstName'].' <'.$_POST['Email'].'> '. "rn" .
'Content-type: text/html'. "rn" .
'X-Mailer: PHP/' . phpversion();
mail($toEmail,'New Form Mail From Your Website',$message,$headers);
$submitted = true;
<!doctype html>
    <meta charset="utf-8">
    <title>PHP ReCaptcha Test</title>
.error { color:#900; }
    // If the form has been submitted successfully , show this information
    if ( $submitted == true ) { ?>
    <h3>Thank You!</h3>
    <p>Your message has been received. We will get back to you within the next 2 business days.</p>
    <? } 
    //Otherwise we show this information
    else { 
    <script type="text/javascript">  
    // Completely unnecessary - changes the theme.
    var RecaptchaOptions = {  
       theme : 'clean'  
    <form method="post" action="" id="contact_form">
        //If we do have errors, loop through our errors array and let the user know what they did wrong.
        if ( isset($errors) ) {
            <div id="formErrors" class="error">
                    <?php foreach ( $errors as $anError ) echo '<li>'.$anError.'</li>'; ?>
        <table border="1" cellpadding="5" cellspacing="5">
                <td>First Name:</td>
                <td><input type="text" name="FirstName" value="<?php echo $_POST['FirstName']; ?>" /></td>
                <td>Last Name:</td>
                <td><input type="text" name="LastName" value="<?php echo $_POST['LastName']; ?>" /></td>
                <td><input type="text" name="Email" value="<?php echo $_POST['Email']; ?>" /></td>
                <td><textarea name="Comments" cols="40" rows="10"><?php echo $_POST['Comments']; ?></textarea></td>
                <td><?php echo recaptcha_get_html($publickey, $error); ?></td>
                <td><input type="submit" value="Send Message" /></td>
    <?php }; ?>

Working Demo

File Download

Download form.txt