PHP Captcha

Before start working with user input by accessing HTML forms, we need to ensure that these inputs are entered manually by a human. Or else, people can submit bulk unwanted data though cron like program execution or any tools, which will create serious issues like, increasing server load, getting spam data and etc.
For that, we can create special code called captcha using PHP script to get rid of these issues. This article deals with some simple steps for creating such PHP captcha code.

Steps in Creating PHP captcha

  • Create captcha
  • Add captcha into HTML form
  • Compare captcha code
Now, we are going to get into the above steps one by one. For that, we have taken PHP contact form in which the captcha code is to be put to prevent from getting spam data.

Create captcha

For ease understanding, We can further split this step into the following list of functionalities we need to perform.
  • Start session to get PHP session_id before sending header to the browser. This is for using PHP global variable, $_SESSION to store captcha code with appropriate array index.
    session_start();
  • Generate random alpha numeric character string using PHP features.
    $random_alpha = md5(rand());
    $captcha_code = substr($random_alpha, 0, 6);
  • Creating new image as target layer as we have done on resizing image using PHP. On top of this layer, we need to fill the random alpha numeric character string we have generated.
    $target_layer = imagecreatetruecolor(70,30);
  • Fill captcha code into the image layer after adding properties like image background, text color and etc.
    $captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
    imagefill($target_layer,0,0,$captcha_background);
    $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
    imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
  • Sending image header with mime type to the browser.
    header("Content-type: image/jpeg");
    imagejpeg($target_layer);
So, the entire code to return captcha code to the target is shown below by recollecting the above steps. And, save this code as captcha_code.php
<?php
session_start();
$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);
imagefill($target_layer,0,0,$captcha_background);
$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");
imagejpeg($target_layer);
?>

Add captcha into HTML Contact Form

To add PHP captcha code into the required HTML form, we need to refer the corresponding PHP file for the image tag src property. Here, we should add an image tag which refers captcha_code.php file, for the contact form. So, the HTML code for the contact form can be modified as follows.
<html>
<head>
<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<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>
<tr class="tablerow">
<td>Name<br/><input type="text" name="userName"></td>
<td>Email<br/><input type="text" name="userEmail"></td>
</tr>
<tr class="tablerow">
<td colspan="2">Subject<br/><input type="text" name="subject" size="73"></td>
</tr>
<tr class="tablerow">
<td colspan="2">Content<br/><textarea name="content" cols="60" rows="6"></textarea></td>
</tr>
<tr class="tablerow">
<td colspan="2">Captcha Code<br/><input name="captcha_code" type="text"><br>
<img src="captcha_code.php" /></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

Compare captcha Code

On form submit, we should verify user entered captcha code, by comparing it with the corresponding $_SESSION entry we have set while creating captcha. If match found, then, the user is recognized as human and allowed further to get access with the page. Otherwise, some negative acknowledgement will be sent. So, the following code should be added on top of the HTML code shown above.
<?php
session_start();
$conn = mysql_connect("localhost","root","");
mysql_select_db("phppot_examples",$conn);
if(count($_POST)>0) {
if($_POST["captcha_code"]==$_SESSION["captcha_code"]){
$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']. "')");
}
else{
$message = "Enter Correct Captcha Code";
}
}
?>
On successful form submission, user feedback, query or anything entered by this contact form will be stored into the database table. For that, we need to fulfill the corresponding database requirements before executing this program.
Download PHP Captcha Source Code

Comments

Popular posts from this blog

Script For Login, Logout and View Using PHP, MySQL and Bootstrap

Real-Time Web Interface to MQTT using Socket.io and Node.js

Customize radio buttons and checkboxes with CSS sprites