This is a simple captcha script which we will use to develop using PHP and GD library functions. To keep the script simple we have not used many powerful tools available in GD library. After understanding this basic tutorial we can go for advance captcha generation script.
There are three files used,
captcha-demo.php , the main PHP script which generates the captcha image.
captcha-demo1.php , the form which display the captcha image generated by above PHP script
captcha-demo2.php, output of is displayed once the user submit the form.
We will discuss each file but before that you can check the demo here.
Download source code of this demo at end of the page
Inside PHP script first we will destroy any previous session and then crate a new session which we will use to store random string. This randomly generated string we will add to our image and ask the visitor to read and enter in the text box provided.
unset($_SESSION['my_captcha']); // destroy the session if already there
We store the randomly generated string in a session variable and we use the same string to generate the captcha image. The session variable is available in our captcha-demo2.php page where we match both data in session variable and user entered string.
$random_text= substr($string,0,8); // change the number to change number of chars
$im = @ImageCreate (80, 20)
or die ("Cannot Initialize new GD image stream");
$background_color = ImageColorAllocate ($im, 204, 204, 204); // Assign background color
$text_color = ImageColorAllocate ($im, 51, 51, 255); // text color is given
ImageString($im,5,5,2,$_SESSION['my_captcha'],$text_color); // Random string from session added
ImagePng ($im); // image displayed
imagedestroy($im); // Memory allocation for the image is removed.
We have a simple web form inside which we will include the PHP file captcha-demo.php to display the image.
<title>Demo of a form showing Captcha image with random string to user read and enter</title>
img = document.getElementById("capt");
img.src="captcha-demo.php?rand_number=" + Math.random();
We have added one button to reload the image by user if required. Now once user submit the form the details will be displayed at captcha-demo2.php file. This file collects all the form data and using one if condition check if captcha string ( present in the session variable ) is same as user entered string or not.
<!doctype html public "-//w3c//dtd html 3.2//en">
<title>demo of displaying form value showing captcha image</title>