Back To Resources, Guides and Information

Free Code: ReCaptcha Form Validation With PHP

This was posted on 08/06/2012 and was filed in Tips And Tricks, Guides and Information, PHP, Code Snippets | (4 Comments)

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

<?php
/*
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>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP ReCaptcha Test</title>
    <style>
.error { color:#900; }
</style>
</head>
<body>
 
<?
    // 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'  
    };  
    </script>  
    
    <form method="post" action="" id="contact_form">
        <?php 
        //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">
                <h3>Errors!</h3>
                <ul>
                    <?php foreach ( $errors as $anError ) echo '<li>'.$anError.'</li>'; ?>
                </ul>
             </div>   
           <?
    
        }
        ?>
        <table border="1" cellpadding="5" cellspacing="5">
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="FirstName" value="<?php echo $_POST['FirstName']; ?>" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="LastName" value="<?php echo $_POST['LastName']; ?>" /></td>
            </tr>
            <tr>
                <td>E-Mail:</td>
                <td><input type="text" name="Email" value="<?php echo $_POST['Email']; ?>" /></td>
            </tr>
            <tr>
                <td>Comments:</td>
                <td><textarea name="Comments" cols="40" rows="10"><?php echo $_POST['Comments']; ?></textarea></td>
            </tr>
            <tr>
                <td>Captcha</td>
                <td><?php echo recaptcha_get_html($publickey, $error); ?></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Send Message" /></td>
            </tr>
        </table>
    </form>
    
    
    
    <?php }; ?>
</body>
 
 

Working Demo

File Download

Download form.txt

Have I Helped You? Share Some Love!

Comments

Showing All Comments

on 04/20/2012:

I will be posting an update to this within the next few days that contains a few requested enhancements, including a 'Reply-To' address and email validation.

NG on 04/10/2012:

Awesome! How can I validate email instead enter email address. Thanks.

on 02/18/2012:

You're very welcome!

Hans on 02/16/2012:

Fantastic job.Thank you.Exactly what I was looking for.

Comment On This

Comments Have Been Disabled.

© Max Morgan Design 2009 - 2014 | Page Generated In 0.61421 Seconds Using 29 MYSQL Queries