PHP Captcha

When allowing users to enter data into our website, we need to check whether the data is entered by the human. Otherwise, people will use robots to push the bulk of unwanted data into the website. It will cause a lot of problems like XSS attack or increase server load to down the website. CAPTCHA is one of the methods to prevent robots from entering data. CAPTCHA can be text-based, audio-based or graphics-based random code generated dynamically. On submitting user input, this code will be mandatory which will help to capture robot not entering captcha code.

In this tutorial, I have a contact form to get the user input. This form includes name, email, message subject and message body fields to get messages from the user. I have created a random captcha code and stored it in a session. This captcha code will be displayed in the contact form which should be entered by the user to submit their messages. I have the server side validation to check whether the code is not empty and valid.

View Demo


PHP code to Create CAPTCHA

In this section, I cover the PHP code for creating CAPTCHA code to be stored in a session variable. I start the session to store the captcha which is dynamically created using the PHP rand() function. I have created an image target layer and write the random code. This JPEG captcha image will be shown in the contact form. The image creation and resizing code are shown as below.

$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");

Add captcha into HTML Contact Form

This code shows the HTML contact form with the CAPTCHA code.

<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<form name="frmContact" method="post" action="">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">
<tr class="tableheader">
<td colspan="2">Enter Contact Information</td>
<tr class="tablerow">
<td>Name<br/><input type="text" name="userName"></td>
<td>Email<br/><input type="text" name="userEmail"></td>
<tr class="tablerow">
<td colspan="2">Subject<br/><input type="text" name="subject" size="73"></td>
<tr class="tablerow">
<td colspan="2">Content<br/><textarea name="content" cols="60" rows="6"></textarea></td>
<tr class="tablerow">
<td colspan="2">Captcha Code<br/><input name="captcha_code" type="text"><br>
<img src="captcha_code.php" /></td>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>

Compare Captcha Code

On form submit, we should verify the captcha code, by comparing it with the corresponding $_SESSION variable. If match found, then, the user is recognized as human and the user information will be processed in the PHP file. Otherwise, Captcha validation error message will be displayed to the user. The code for validating the captcha is,

$conn = mysql_connect("localhost","root","");
if(count($_POST)>0) {
$message = "Your message received successfully";
mysql_query("INSERT INTO tblcontact (user_name, user_email,subject,content) VALUES ('" . $_POST['userName']. "', '" . $_POST['userEmail']. "','" . $_POST['subject']. "','" . $_POST['content']. "')");
$message = "Enter Correct Captcha Code";


Following screenshot shows the random captcha code in the contact form.


View DemoDownload

This PHP code tutorial was published on July 31, 2013.

↑ Back to Top