Create your own php capcha script in 10 min

Spam protect your form with php captchaSpam is unfortunately a problem for many webmasters. One of the favorite methods for spammers is to use web forms without any kind of spam protection.

A form can be spam protected very effective by adding a captcha field that requires the user to enter a security code before the form can be submitted.

In this post you’ll learn to create a simple PHP based form that has a built in captcha for spam protection.

Step 1 – background image

First you need to have a background image that you can use for your captcha image. In the example we’re using the following image, but you can use any picture you like.

capcha image background

When you have found the right image, upload it to your server. To make things simple, you can upload the image to the same place where your plan to place your captcha script. In this example the name of the image is “security.jpg”

Step 2 – Create the captcha image

Now that we have a background image, we need to create a piece of PHP code that writes random letters and digits on the image, so we’re getting a captcha image.

The code below writes 5 random digits/letters on the background image. You can change the length of the captcha code by changing the values in $ResultStr.

To add a little noice in the image, that makes it more difficult for simple image recognition programs to extract the code, the script also draws two white lines.

Last but not least, the script writes the values captcha values from the image as session variables, that later can be used to control, if the user enters the right captcha code.


$RandomStr = md5(microtime());// md5 to generate the random string

$ResultStr = substr($RandomStr,0,5);//trim 5 digit

$NewImage =imagecreatefromjpeg("security.jpg");//image create by existing image and as back ground

$LineColor = imagecolorallocate($NewImage,233,239,239);//line color
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);//text color-white

imageline($NewImage,1,1,40,40,$LineColor);//create line 1 on image
imageline($NewImage,1,100,60,0,$LineColor);//create line 2 on image

imagestring($NewImage, 5, 10, 5, $ResultStr, $TextColor);// Draw a random string horizontally

$_SESSION['key'] = $ResultStr;// carry the data through session

header("Content-type: image/jpeg");// out out the image

imagejpeg($NewImage);//Output image to browser


Save the code to a file eg. captcha.php, and upload the code to your server.

You can already test the code now. direct your browser to http://www.<yourdomain>.com/<path to captcha script>/captcha.php

If everything works, you will now see a image like this, that consists of the background with 5 random letters written on top of the background image:

Capcha image with code and noice

See example here

If no image is displayed, you might need to check if the  image filename and location in the script is right.

If the script returns a image like above, you can proceed to the final step.

Step 3 – Building the form

Finally we need to embed the captcha functionality in a form.

The captcha image is displayed by adding the following line in the form <img src="captcha.php" alt="captcha image"/>. In this example the captcha value is taken from the input field named: "number"

To capture and validate the capture code a  session_start(); is included at the very beginning of the page.

Next we need to compare the value entered by the user, with the value displayed in the image:

 $number = $_REQUEST['number'];

 // you can create a lot of different checks and then give each of them a text that will be displayed to the user
 $err[]='Invalid captcha code entered<br>';

If the two values are different (a valid captcha code hasn’t been entered) a error message will be displayed to the user, and the form will not be submitted.

If the values are identical, the form will be submitted.

The final script for the form looks like this:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="en" lang="en">
<title>Test of PHP Captcha for form</title>

if ($mode == "anbefal") {
 $number = $_REQUEST['number'];

 // you can create a lot of different checks and then give each of them a text that will be displayed to the user
 $err[]='Invalid captcha code entered<br>';

 if ($err > 0) { // display error messages
 echo ("<h3>Error!</h3>");
 echo ("Please correct the following error(s): <br/><br/>");
 $numElements = count($err);
 for($counter=0; $counter < $numElements; $counter++) {
 print "$err[$counter] ";
 echo ("<br/><a href=\"javascript:history.go(-1)\">Click here to go back</a>");

 } else {

 echo ("<h3>This works fine</h3>");
 echo ("A correct captcha code has been entered and the form can now be processed");
} else {

<h3>Captcha test</h3>
 <form method="post" action="<?php echo $PHP_SELF;?>">
 <td>Your name:</td><td><input type="text" name="navn"/></td>

 <td>Repeat code from image:<br/><img src="captcha.php" alt="captcha image"/></td><td valign="top"><input type="text" name="number"/></td>
 <td colspan="2"><input type="hidden" name="mode" value="anbefal"/><button value="submit"><span>Submit</span></button></td>


You can try the final form here

The current form is pretty basic, but you can easily add some nice styling to the form  and additional form fields.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

2 Replies to Create your own php capcha script in 10 min

  1. Kiera Dedek says:

    Great points on software. Thrilled to have located your site and add it to my reader. Cheers!

Trackbacks for this post

  1. Tweets that mention Create your own php capcha script in 10 min | Tips4PHP --

Comments are now closed for this article.