subscribe via rss subscribe via mail subscribe via twitter

How To Implement reCaptcha With Your PHP Project

Posted in PHP, October 26th, 2009 and has 28 comments

reCATPTCHA

It’s right that spamming can be a huge problem. But you can prevent your site from being spammed by following several solutions such as giving the visitor a captcha field to fill in order to verify if he is human. Or by blocking the IP of the spammer with php if you know their IP. Today I will show you how to get started with reCAPTCHA. “reCAPTCHA is a free CAPTCHA service that helps to digitize books, newspapers and old time radio shows. Check out our paper in Science about it”.

Demo | Download

1. Go To reCaptcha.net

Captcha

Now click on “use reCAPTCHA on your site” and follow the registration steps. Once you are done, click on “My Account” in the left menu. a button appears.

Add a New Site

Click on it and add your website. When you finish, you will be redirected to a page contains your “Public Key” and your “Private Key”. keep in your mind that your Private Key is must be kept as secret, so don’t share it with everyone. Also you need to have a key for every website. No matter if it is a sub-domain.

2. Download The Required Files

You have to download the required files to make reCaptcha works on your website.Here is a direct link. You have just to upload them to your website via FTP.

3. Implement The Code With Your Script

<?php

// call the lib..
require_once('recaptchalib.php');

// Get a key from http://recaptcha.net/api/getkey
$publickey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$privatekey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

# was there a reCAPTCHA response?
if ($_POST["submit"]) {
    $response = recaptcha_check_answer($privatekey,
	    $_SERVER["REMOTE_ADDR"],
	    $_POST["recaptcha_challenge_field"],
	    $_POST["recaptcha_response_field"]);

        if ($response->is_valid) {
                echo "Yes, that was correct!";
        } else {
                # set the error code so that we can display it
		echo "Eh, That wasn't right. Try Again.";

        }
}
?>
    
<form action="index.php" method="post">
<?php echo recaptcha_get_html($publickey, $error); ?>
<input style="width: 317px" type="submit" value="submit" name="submit"/>
</form>

Let’s Explain the code.

require_once(‘recaptchalib.php’);

As you can see I called the “recaptchalib.php” which i downloaded it from reCaptcha.net this is the only file we need to make the script works.

// Get a key from http://recaptcha.net/api/getkey
$publickey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$privatekey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

Now replace the XXX with your keys from reCaptcha.net

<form action="index.php" method="post">
<?php echo recaptcha_get_html($publickey, $error); ?>
<input type="submit" value="submit" name="submit"/>
</form>

In this form i have set the action to index.php which is the same file we are working with. and the method is set to ‘post’. To get the reCaptcha box you have to call the function recaptcha_get_html() and as you can see it calls the $publickey which is important. The $error isn’t necessary here.

# was there a reCAPTCHA response?
if ($_POST["submit"]) {
    $response = recaptcha_check_answer($privatekey,
	    $_SERVER["REMOTE_ADDR"],
	    $_POST["recaptcha_challenge_field"],
	    $_POST["recaptcha_response_field"]);

        if ($response->is_valid) {
                echo "Yes, that was correct!";
        } else {
                # set the error code so that we can display it
		echo "Eh, That wasn't right. Try Again.";
        }
}

Now we make sure that $_POST["submit"] is not empty. if so, recaptcha_check_answer() is going to do the job. it accepts 4 parameters which are:

$privatekey – Your Private key.
$_SERVER["REMOTE_ADDR"] – The visitors IP Address.
$_POST["recaptcha_challenge_field"] – a hidden reCaptcha input.
$_POST["recaptcha_response_field"] – The returned value from the reCaptcha’s input box.

And then we use $response->is_valid to verify if the entered Captcha is right or wrong. That’s all for this tutorial, leave your comment for any suggestions.

Demo | Download

Author

Mohamed Amine is a university student. He lives in Algeria, Algiers. He is interested in PHP, jQuery, and Css. He likes to play Bowling and Pool. You can follow him on Twitter and Facebook.

What's next? Help us to share this.

Comments

Want to show an avatar next to your comments? Join Gravatar.
  • Good tutorial! It’s refreshing to see a simple recaptcha tut out there for the php beginners and those of us without the time to wade through documentation. :-) Thanks for doing it!

  • seamus said:

    I can’t get the thing to work. My reg form is in a template .tpl file so i cannot rename it to .php or insert php tags to display the reCAPTCHA image.

    I have registration.php which process the form, but the reCaptcha box has to be called before the submit button in form with the function recaptcha_get_html() and $publickey.

    Im lost – any help wud be great.

    seamus

  • Dear Amine, it’s very important and helpful to every programmers to secure the site. so I salute you to post this type of article.

  • @Steven Wiggins
    yeah actually, this was the idea :)

    @seamus
    What CMS are you using?

    @Zamshed Farhan
    Thanks for your comment, much appreciated.

  • Thanks, this blog aided me in solving some issues with the latest release, Why do they always seem to leave out vital information when they upgrade? It may be minor to them but not for us! I’m sure i’m not alone.

  • Good share, great article, very usefull for us¡­thanks.

  • Paul said:

    Hey thanks so much for this, the tutorials on reCAPTCHA’s own site didn’t actually work for me, but i stuck this into the php i had already used and got it running straight away.

    Like Steven already said, it’s refreshing to have a simple tutorial for those of us who aren’t that good when it comes to understanding code, i myself am an artist who struggles to understand this sort of thing!

    Cheers again

  • @Paul
    Thanks buddy for cheering up! I appreciate your comment.

  • How can we modify where the error message goes?

  • Never mind, I figured it out. Just had to put the PHP code inside a div.

    is_valid {
                    echo "";
            } else {
                    # set the error code so that we can display it
            echo "Your reCaptcha was incorrect. Try again.";
            }
    }
    
  • Ignore that code I only part of it posted for some reason.

  • This would be more helpful if there was a “normal” field in the form such as First_Name.

  • Matt said:

    I’m having some problems understanding this. I currently have my contact page (contact.htm) which posts to ‘webformmailer.asp’

    How do I use your sample code to have my contact form pass along user input to be processed by webformmailer.asp only after a valid recaptcha response? I’m lost!

  • Matt said:

    I’m assuming that to use this code with my form (renamed contact.php to account for the php code), the valid response condition must pass the form data to be processed by ‘webformmailer.asp’, instead of simply returning to index.php and displaying the text “Yes, that was correct!” as is the case with the code presented on this page – am I correct?

    I don’t know php so I don’t know how to code for a valid response!

    Any advice would be greatly appreciated – thank you!!

  • @Dave Barnes
    Sorry if the code isn’t clear enough. I know that things at the beginning can seem pretty complicated. However, if you play with the code a bit you might get things work properly.

  • @Matt
    I hope that I got your idea. Why are you using two files? you can combine them into one file and make it much easier to work with.

    However, in your situation, I would modify the file called “contact.php” and insert this code + your own modifications.

    <?php
    // contact.php - this is your file.
    // call the lib..
    require_once('recaptchalib.php');
     
    // Get a key from http://recaptcha.net/api/getkey
    $publickey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    $privatekey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    ?>
    <-- end of code, your html form must be somewhere here -->
    

    okay, now let’s talk about the other page, which is “webformmailer.php” it has to be in php

    # was there a reCAPTCHA response?
    if ($_POST["submit"]) {
        $response = recaptcha_check_answer($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);
     
            if ($response->is_valid) {
                    // send your email now (:
            } else {
                    // error message, wrong captcha!
            }
    }
    ?>
    
  • Matt said:

    Ok, I’ve chosen not to use my hosting provider’s asp mailer and have made a basic php version that i can pop the recaptcha code into. Thanks for the help!!

  • Praveen said:

    This code does not work the first time its executed. When I hit the submit button, it then complains that the code is wrong and puts up the recaptcha box and the error. IE does not even bring up the form saying that the form has errors. Firefox, on the other hand, will display the page but with only the submit button the first time the page is launched. on subsequent reloads, it will display the box and other info without any problems. Any ideas why IE might be doing that or why Firefox does not display the box the first time?

    Thanks

    p

  • Jim Camomile said:

    Thanks for the demo files. That helps a bit. Other than that, this tutorial is much like the documentation available from recaptcha. What I am trying to understand and not getting so far is how to make the form do what it is supposed to do if the challenge is completed. This and all other tuts and docs simply end by echoing a line like “Yes, that is correct”, but that isnt what a real user is looking for when they submit a form. What is needed is a real life example of submitting a form if all is correct.

  • onur erten said:

    Great guide though. But i couldn’t managed to connect this recaptcha to my download link, though my download link works even i don’t enter the captcha words. Any suggestions?

  • Martin said:

    Hi, I downloaded and implemented everything from the recaptcha site and all is working. Except when I tried and retain the variables so the form doesn’t reset if the recaptcha is entered incorrectly, the variables dissappear , as if the recaptcha erases them. I am setting them here:

    e.g.

    if (!$response->is_valid) {
                   $var = $POST['var'];
            }
    
    

    Please can you help? thanks

  • rehman said:

    i cant able to download the phplib file. whenever i try to click the download link it saying “your search does not generate any results”

  • Raj said:

    Excellent information on recaptcha implementation. need more if the recaptcha failure retain the values and refresh pages.. Thanks in advance

  • Dolly said:

    I’d like to have the error message integrated in the form itself next to the input field instead of on a redirected white empty page. How would this be possible? (Unfortunately I am not a programmer so don’t have any clue how to mix things).
    Thanks a lot in advance.

  • Girish Zope said:

    Notice: Undefined index: submit in C:\wamp\www\recaptcha-tut\index.php on line 12

    Thesse error are shown on my recaptcha page, please any one can help me??

  • Renown web said:

    Thank you very much it works for me..

  • danie said:

    Wish I knew how to apply this on two forms on the same page, any advice or tips to achieve this?

Follow Discussion

Trackbacks

Leave a Reply