PHP Add Captcha Protection To Web Forms

Cpanel/Whm License $3/mo Plesk License $10/mo Cloudlinux License $5/mo

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>

<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

You can see working captcha example by visiting this url.

Further readings:

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Related posts

Zuckerberg to Study Crypto in Quest to Fix Facebook

SXI ADMIN

Zooko Wilcox Envisions ‘Ambitious’ Changes for Zcash Cryptocurrency

SXI ADMIN

ZombieChain Comes Alive: Can Ethereum Sidechains Save the Dapps?

SXI ADMIN

ZoKrates Seeks to Bring Best of Zcash to Ethereum with Devcon Debut

SXI ADMIN

Zk-Starks? New Take on Zcash Tech Could Power Truly Private Blockchains

SXI ADMIN

Zk-Snarks Everywhere: Ethereum Privacy Tech Hits Tipping Point

SXI ADMIN

ZipZap to Offer Cash-for-Bitcoin Service at 28,000 UK Locations

SXI ADMIN

ZipZap Resumes Cash-to-Bitcoin Services for UK Shoppers

SXI ADMIN

ZipZap Raises $1.1 Million to Grow Global Bitcoin Payments Network

SXI ADMIN

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More