≡ Menu

PHP Add Captcha Protection To Web Forms

I own a small business website. However, bots started to abusing my forms such as contact.php. How do I stop bad bots from abusing my site? How do I tell if PHP form is submitted by a person or a script?

You need to use a Captcha, which is nothing but a type of challenge-response test used by you to ensure that the response is not generated by a bot. There are plenty of libraries provided for PHP. I recommend the reCAPTCHA PHP Library, which provides a simple way to place a CAPTCHA on your PHP forms. It can stop bots from abusing it. you need to use the reCAPTCHA API.

Step # 1: Get reCAPTCHA API Library

Visit reCAPTCHA website to sign up for an API key (it is free). Please note down your private and public keys.

Step # 2: Download and Install reCAPTCHA PHP

Download the reCAPTCHA library from Google code repo:
$ cd /tmp
$ wget http://recaptcha.googlecode.com/files/recaptcha-php-1.10.zip

Unzip recaptcha-php-1.10.zip, enter:
$ unzip recaptcha-php-1.10.zip
Finally, copy recaptchalib.php to the directory where your forms live. For e.g. if your contact.php is at /var/www/html, copy recaptchalib.php as follows:
$ cp /tmp/recaptcha-php-1.10/recaptchalib.php /var/www/html

Step # 3: Test It

Create a php script as follows:

<html>
<head>
	<title>Sample Email Form</title>
</head>
<body>
 
 
<script>
    function checkForm() {
	if (document.forms.myphpform.elements['yname'].value.length == 0) {
		alert('Please enter a value for the "Name" field');
        	return false;
    	}
	if (document.forms.myphpform.elements['email'].value.length == 0) {
		alert('Please enter a value for the "Email" field');
        	return false;
    	}
	if (document.forms.myphpform.elements['message'].value.length == 0) {
		alert('Please enter a value for the "Message" field');
        	return false;
    	}
 
        return true;
   }
</script>
 
 
<form action="?done=1" method="post" name="myphpform" onSubmit="return checkForm()"  >
<table border=0>
	<tr>
		<td>Your Name:</td> <td><input type="text" name="yname" size="50" maxlength="50" value="" /></td>
	</tr>
 
	<tr>
		<td>Your Email:</td> <td><input type="text" name="email" size="50" maxlength="50" value="" /></td>
	</tr>
 
	<tr>
		<td>Message:</td> <td><input type="text" name="message" size="50" maxlength="50" value="" /></td>
	</tr>
	<tr>
		<td>Are you a human being?</td>
		<td>
<?php
 
@require_once('recaptchalib.php');
$publickey = "YOUR-PUBLIC-KEY";
$privatekey = "YOUR-PRIVATE-KEY";
 
$resp = null;
$error = null;
 
# are we submitting the page?
if ($_POST["submit"]) {
  $resp = recaptcha_check_answer ($privatekey,
                                  $_SERVER["REMOTE_ADDR"],
                                  $_POST["recaptcha_challenge_field"],
                                  $_POST["recaptcha_response_field"]);
 
  if ($resp->is_valid) {
	$to="you@example.com";
	$subject="Feedback from example.com";
        $body=" Message via webform:
 
Name: " .$_POST["yname"] . "\n
 
Email: " .$_POST["email"] . "\n
 
Message: " .$_POST["message"] . "\n";
        /*  send email */
	mail($to,$subject,$body);
	echo "<p>Email sent!</p>";
	exit(1);
 
  } else {
     	echo "Sorry cannot send email as you've failed to provide correct captcha! Try again...";
  }
}
echo recaptcha_get_html($publickey, $error);
?>
		<td/>
	</tr>
	<tr>
		<td>&nbsp;</td>
		<td><input type="submit" name="submit" value="submit" /></td>
	</tr>
</table>
</form>
</body>
</html>

Sample Output:

Fig.01: PHP Captcha in Action

Fig.01: PHP Captcha in Action

You can see working captcha example by visiting this url.

Further readings:

Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 26 comments… add one }

  • Younten Jamtsho June 25, 2009, 3:22 am

    Nice post… have been looking for such kind of CAPTCHA in PHP

  • someone July 14, 2009, 11:17 pm

    Gosh, your code is ugly and vulnerable, full of security bugs. I would recommend you to re-implement with zend framework with you are not a hard code php person.

    • Truth July 14, 2011, 3:34 am

      Some guys are just stupid “Mr. Someone” I’m writing this to you, if you think you better, then contribute what you have than criticizing what the good Samaritan is doing. However, I much appreciate the author’s works. God bless him.
      A word to the Author: Keep your head up man, and thank you for your lovely work, God bless you abundantly.

      • Jojo Pogi January 18, 2012, 8:15 am

        hey ‘mr. someone’… are you a php hard coder? then why don’t you create one for yourself…and it’s obvious that the reason you are here is because your looking also for a solution in your captcha problem… that shows you can’t do it urself… moron!… advice: dont criticize someone’s good intention, look at yourself first.. i dont think your good at php and one more thing… i know im better that you asshole. haha… hey author, good contribution there keep it up!! nice work

        • a different someone January 18, 2012, 3:01 pm

          I’m glad I’m still getting emails from this comment section so someone named jojo can insult someone named ‘someone’ many months later…

  • Michael Montgomery September 22, 2009, 5:54 pm

    I just came across this article: Feel I want to comment on @someone ‘s comment.
    ** You’re an ASS**
    The Author took the time to write a good solid article. If you don’t approve or like.
    At least give constructive comment

    Michael

  • Anton November 22, 2009, 6:23 am

    What if I’m unable to save any of the unziped library files to the hosting server?

    Are you sure there’s a way for me to use this CAPTCHA feature on my web forms? Thanks.

  • ainni January 17, 2010, 5:33 pm

    realy nice its working thx …

  • mackenzie February 17, 2010, 9:23 pm

    how can I get the “Email Sent” response to show up and not kill my footer.php file?

  • Iuliu March 9, 2010, 5:13 pm

    hy,
    i installed captcha on one of my forms and when i tipe the wrong word in the box and i click on send button it drives me to a blank page witch tells me that captcha is incorrenct and i have to click back.
    all i want is to appear like on this page http://recaptcha.net/learnmore.html to reload only the captcha, not the entire page, and to remain on the same page.
    please help me :(

  • Business Website August 8, 2010, 4:10 am

    Adding a captcha to blog comment form and on other registration can minimize the usage software to spam your website and because of that it can lessen your job. Thanks for the great tutorials.

  • ozc September 4, 2010, 5:42 pm

    This would be good for embeding in existing embedded webpages if it had a few improvements.
    A couple of suggestions.
    -Give it a real “from” email address instead of having yourhostingaccount.com appear.
    -Included a clear form button. (easy enough even for me to add)
    -Instead of having it reload the page and adding a “?done=1” have it do the following
    a.replace the recapatcha/clear/submit buttons with a green box saying “successfully sent” without refreshing the page.
    b.If a field is empty have a popup dialog box saying fill in such and such.

  • ata April 19, 2011, 5:43 pm

    i use it and it works well
    but i have a big problem :(
    when i insert a wrong value in captcha fld and press submit , no error will show and whole form works without any error !

  • Maria June 23, 2011, 5:36 pm

    I just copied and pasted and works for me (adding my public and private key and my email). This is a good idea of how to use it.
    Thanks

  • Dinesh@Programming Online with Source Codes December 31, 2011, 3:58 pm

    Thanks VIVEK GITE …. Awesome post of you with proper source code and outputs.. I was searching for this from near about 2 years. I found official site but can;t understand code.. This helped me a lot… R u from India ???

  • Hardik March 6, 2012, 10:29 am

    This is really ow some and save my valuable time only 5 min and reCAPTCHA is in your form enjoy..

  • Collins March 19, 2012, 11:19 pm

    instead of “email sent!” , how can i get this to go to another page when its sent?

  • Collins March 19, 2012, 11:27 pm

    how can I get the “Email Sent” response to show up and not kill my footer.php file?

  • waheed April 24, 2012, 4:44 pm

    Its very very Nice post… have been looking for such kind of CAPTCHA in PHP

  • Mark Codes May 15, 2012, 1:55 pm

    Hi,

    Private key is visible on view page source. How can I hide it?

  • Codeblues Girl May 30, 2012, 8:34 pm

    THANK YOU!!! This solved my problem!

  • Rick June 18, 2012, 10:36 pm

    Hi,
    Nice article, I learned who to build my site using MS Expressions Web 4, but there is no way I could get reCAPTCHA to work until reading and using your code.
    But how do I hide my private key number? Any help with hiding my private key would be greatly appreciated.
    Thanks
    Rick

  • monster headphones beats October 4, 2012, 2:25 pm

    Thanks for helping out, exceptional info.

  • Marek March 17, 2013, 1:47 am

    doesn’t work for me “Could not open socket”, any idea?

  • Biswajit Paul December 16, 2013, 5:16 pm

    Getting ERROR like below:
    Notice: Undefined index: submit in E:\iWork\CSS\ZIP_1\Captcha\recaptcha\index.php on line 54

  • maral May 27, 2014, 11:23 am

    i cant see recaptcha form in my website!
    doese in becouse of my public key?

Leave a Comment