Back To Resources, Guides and Information

Free Code: ReCaptcha Form Validation With PHP

This was posted on 06/30/2011 and was filed in Tips And Tricks, Guides and Information, PHP, Code Snippets | (6 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.

The Code

<?php

//Make sure you put your keys here
$publickey = 'YOUR KEY HERE';
$privatekey = 'YOUR KEY HERE';
$toEmail = 'YOUR EMAIL HERE';
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.
    foreach ( $_POST as $k => $v ) $_POST[$k] = htmlentities(stripslashes($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) ) {
        $headers = 'Content-type: text/html'; // Allows us to put html in comments
        $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($toEmail,'New Form Mail From Your Website',$message,$headers);
        $submitted = true;    
    } else {
        //If we do have errors, loop through our errors array and let the user know what they did wrong.
        ?>
        <div id="formErrors">
            <h3>Errors!</h3>
            <ul>
                <? foreach ( $errors as $anError ) echo '<li>'.$anError.'</li>'; ?>
            </ul>
         </div>   
       <?
    }
    
    
}
// 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="">
    <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 }; ?>

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.

dsd on 04/10/2012:

sdsds

Sondra on 04/01/2012:

thank you!!! I was looking for something this awesome

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

© Max Morgan Design 2009 - 2012 | Page Generated In 0.24284 Seconds Using 42 MYSQL Queries