PHP script for creating the CAPTCHA functionality

You can see CAPTCHA (“Completely Automated Public¬†Turing test¬†to tell Computers and Humans Apart”) functionality on many websites to prevent spam contents. CAPTCHA is used exclusively in applications where the user input is required. These applications include Blogs, Forums and Portals.

In this article I will demonstrate how to create a simple CAPTCHA functionality using php script.
Step 1 : Create image contain text or number or etc which ever you want. Also include like mathematics equation.

We use follwoing function to create image for captcha.

1. imagecreate – Create a new palette based image. imagecreate() returns an image identifier representing a blank image of specified size.

2. imagecolorallocate – Allocate a color for an image. Returns a color identifier representing the color composed of the given RGB components.

3. imagestring – Draw a string horizontally. Draws a string at the given coordinates.

4. imagepng – Output a PNG image to either the browser or a file. Outputs or saves a PNG image from the given image.

5. imagedestroy – Destroy an image. imagedestroy() frees any memory associated with image.

First see above php functions used for create simple image. Now see below simple php script which create captcha image. Save this script in captcha.php file. Use this file in image src attribute to display image. This php script always create random captcha image.

session_start(); # For storing captcha answer.
# Create a 100*30 image
$im = imagecreate(100, 30);

# White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

# we create two random numaber betwwen 0 to 10 to generate one summation operation string.
# Here you can also use string in captcha. You can use whatever you want.
$n1 = rand(1,10); $n2 = rand(1, 10);

# we store sum of two random numaber in SESSION varible which is used to verify user input.
$_SESSION['captcha_value'] = $n1 + $n2; 

# generate summation operation string
$captchaString = $n1." + ".$n2." = "; 

# Write the string at the middle of the image.
imagestring($im, 5, 20, 7, $captchaString, $textcolor);

# Output the image
header('Content-type: image/png');
imagepng($im); # Output a png image.
imagedestroy($im); # To free memory.

Step 2: HTML code where you can use captcha. File name is captchaForm.html

     <head><titile>Test Captcha</title></head>
          <form action="testCaptcha.php" method="post">
              <img src="captcha.php" />
              <input type="text" name="captcha_value" />
              <input type="submit" value="Submit" />

Step 3: Now verify user input. File name is testCaptcha.php

    if($_SESSION['captcha_value'] == $_POST['captcha_value'])
        echo "Verify that you are human.";
        echo "You enter worng captcha value. Please try again.";