How to implement a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) using PHP
Implementing CAPTCHA using PHP

Steps involved in this tutorial:
- Create a background image, the more messier the more better.
- Load a font file to display the CAPTCHA text
- Generate a random unique text
- Store the generated text in a Session variable to be used later for validation
- Write the CAPTCHA text to the image created in Step 1
- Generate the CAPTCHA image
- Also created a php page with the CAPTCHA image, a text box for input and a Submit button to show a working model (this step is not explained in detail, its simple PHP code, download and check the source files)
Click here for a working model
The first thing I did was opened Photoshop and created this image to use as a background image

If you don’t have Photoshop don’t worry, any image editor will do. Even M$ Paint is enough. Just create an image with random colors. Save the image in PNG format with filename captcha.png. If you don’t like PNG , save in the format you like and use the appropriate function to load image.
Ok now the background image is ready.
Using the php function imagecreatefrompng load the image we just created using the code
$captchaImage = imagecreatefrompng("captcha.png");
Next using the php function imageloadfont , load a font to display the CAPTCHA text.
The parameter of the imageloadfont function is a font filename. I tried using a TTF font file. But somehow it doesn’t work. The possible reason for this, from php.net (http://au3.php.net/manual/en/function.imageloadfont.php)
“ The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.”
So I created a GD Font (.gdf) file. You can create a .gdf file from TTF using http://www.wedwick.com/wftopf.exe or http://www.puremango.co.uk/cm_fontmaker_114.php or download some good GDF fonts from http://www.widgnet.com/gdf_fonts/fonts.html
After loading the font the next step is to generate a random, unique string to use as CAPTCHA text. This is how the CAPTCHA text is created
$captchaText = substr(md5(uniqid('')),-9,9);
Generate a string using uniqid(), MD5 it, extract the last 9 characters using substr()
Now store this generated text in some session variable for later validation. You can also store this generated text in a cookie or database instead of a session variable.
Now write this generated string on the background image we created earlier. For this we use the function imagestring()
Output the image in PNG format using imagepng() . Now you will have an image with a random, unique string written in it.
Another advantage of this code is, to display the CAPTCHA image you only need to include a image tag in your webpage and give the source as capthca.php. Then the CAPTCHA image will be displayed.
Eg :
<img src="captcha.php" name="captcha" width="233" height="49" >
I have also created a php file to show its working. You can download the full files with some additional GD fonts here.
<?php /*** * File : captcha.php * Description : Creating a captha image and * store the text in a session variable * Author : Kiran Paul V.J. aka kiranvj aka human * License : Freeware * Last update : 22-Aug-2007 */ // Initialize session data session_start(); // all images in this file is of PNG format, // there is not specific reason for that. // this line is used to set the header of the page // setting the header to image/png means this page // contians data of image->PNG type header("Content-type: image/png"); // create a new image resource from a file $captchaImage = imagecreatefrompng("captcha.png") or die("Cannot Initialize new GD image stream"); //Loads a new font from a file $captchaFont = imageloadfont("anonymous.gdf"); // Create the captcha text with some manipulation $captchaText = substr(md5(uniqid('')),-9,9); // stores the captha text in a session variable $_SESSION['session_captchaText'] = $captchaText; // Allocating color for captcha text to be used // in imagestring function $captchaColor = imagecolorallocate($captchaImage,0,0,0); // drawing the string imagestring($captchaImage,$captchaFont,15,5,$captchaText,$captchaColor); // Outputs the captha image in PNG format. // You can change the image format using // imagejpeg,imagegif ,imagewbmp etc. imagepng($captchaImage); //frees memory imagedestroy($captchaImage);?>

















thnks..
but when i tried to run the captcha.php, it gives error–
Fatal error: Call to undefined function imagecreatefrompng() in C:\Program Files\Apache Group\Apache2\htdocs\captchas\test4\captcha\captcha.php on line 21
and if try to run index.php it’ll not display image..
why this is so..
plz reply..
Hi Abhi,
You are getting that error because GD is not installed in your webserver.
You can check if GD is installed by using phpinfo() function. Open a new PHP page and write this
Call this page from the browser. Check under the section gd for more details. If gd is not installed there wont be any section named gd.
another method to check if gd is installed is
<?php if (extension_loaded('gd') && function_exists('gd_info')) { echo "It looks like GD is installed"; } ?>Hope these helps
If gd is installed your gd section in phpinfo will look like
GD Support enabled
GD Version bundled (2.0.28 compatible)
FreeType Support enabled
FreeType Linkage with freetype
GIF Read Support enabled
GIF Create Support enabled
JPG Support enabled
PNG Support enabled
WBMP Support enabled
XBM Support enabled
Captcha is best protect
Hii Kiran,,
The image is not getting displayed in the page which i embed this captcha.
I’m getting an error like, ” An unhandled win32 exception occured in httpd.exe[4392].”
why is dat happening so? u told tht GD library was not installed, if so how to install it.. please
help me.
Many Thanks,
Pavan.P.
I doubt there is some issue with the installation of apache server. I recommend using WAMP http://www.wampserver.com/en/
Hii kiran,
I’ve installed WAMP server, yeah the problem has been solved..thnx for d come back,
where can i get gdf files?? u’ve provided only 3, if i wanna download more,where can i get them?
how can i add capital letters and symbols to the captcha?
Many thanks,
Pavan.P
hi there, well what if you have a form with you captcha , and for example per day there will be about 1000 users , where user access your captcha code every 3 sec , i suppose that if one user will try to enter captcha at the same time throught two browsers your captcha won’t work in the first one