Captcha generation script in PHP

Captcha generation PHP Script 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 five files used,
  1. captcha-image.php , the main PHP script which generates the captcha image.
  2. captcha-demo1.php , the form which display the captcha image generated by above PHP script
  3. captcha-image-adv.php , PHP script which generates the Advanced captcha image.
  4. captcha-demo2.php , the form which display the Advanced captcha image
  5. captcha-demo-data.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.
Demo of Captcha generation script
Download source code of this demo at end of the page

Captcha validation without reloading the page. By using JQuery we can validate the captcha entry of the user. We will send the data to our backend PHP script and display the output to the user. Here user stays in the same page and status of the validation is shown as message to the user.
  1. captcha-demo3-jq.php , Demo without reloading the page by using JQuery.
  2. captcha-demo3-data-jq.php , Backend PHP Script to receive user entered data & returns the validation output

Demo of Captcha validation without reloading page by using JQuery


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-demo-data.php page where we match both data in session variable and user entered string.
$string= str_shuffle($string);
// change the number to change number of chars
$random_text= substr($string,0,8); 
We change the header of the page as we are sending an image ( not an html code )
In the last part of the script we will create the image using GD library support.
$im = @ImageCreate (80, 20)
or die ("Cannot Initialize new GD image stream");
// Assign background color
$background_color = ImageColorAllocate ($im, 204, 204, 204); 
// text color is given
$text_color = ImageColorAllocate ($im, 51, 51, 255);
// 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-image.php to display the image.
<title>Demo of a  form showing  Captcha image </title>
<script type="text/javascript">
function reload()
img = document.getElementById("capt");
img.src="captcha-image.php?rand_number=" + Math.random();

<body >

<form type=post action=captcha-demo-data.php><input type=text name=t1>
<img src=captcha-image.php id="capt">
<input type=button onClick=reload(); value='Reload image'>
<input type=submit value='submit'>
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-demo-data.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>

<body >
echo "Text as entered by user  : $_GET[t1] <br>";
echo "Captcha shown : $_SESSION[my_captcha] <br>";
if($_GET['t1'] == $_SESSION['my_captcha']){
echo "Captcha validation passed ";
}else {
echo "Captcha validation failed ";



Font size and aligning inside image

We are declaring the height and width here.
$im = @ImageCreate (80, 20) // Width and height of the image.
The text we are placing inside this image here
Inside this function we have Int 5 as font size, Int 5 as X position of text inside Image, Int 2 as Y position. By adjusting these values we can align text to center , increase size of font and better position them.

How to add Text String to Image

At the time of random text generation, we have one option to select number of chars we want to use. This can be changed here.
$random_text= substr($string,0,8); // change the number to change number of chars
Based on the number of chars used, font size and image with the text string can be positioned.

Advance Script to generate complex Images

We can rotate each char inside the image by arbitrary angle. This will make difficult for the robots to read the text inside images. We can add noise by adding random lines to the image. This part is added in advance section.
Demo of Advance Captcha generation script
We have generated each character of the random string as an image and then rotate the same to an arbitrary angle.

How to rotate Image using GD

After rotation of the character ( as Image ) we copy it to our main Image. This process we repeat for each char present in our string. Then we display the final image.

Download source code of captcha generation script


Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net



    thanks a lot


    Simple and easy captch code :D
    Thank you very much!
    Hamza Ayub


    Good Work
    seerin thaj


    It is easy to understand


    How to set the image in center and how to made a font size.?


    Check the line saying


    Here first 5 is the font size, then 5 is the x position.
    Based on the number of text you want to display and the font size you can adjust the x position to keep the text string at center.
    It can be created dynamically but that will make the script complex.


    How to validate this captcha. When user insert wrong input and click submit, error messages will appear but still in the same page


    That requires JQuery, we will develop that in Part II of this script.


    3rd Demo is added, here JQuery is used so page is not reloaded and validation message is shown to the user. This demo is included in Downloaded Zip file.


    Captcha image is not showing


    GD support must be available


    I was trying to add the captcha in my websites contact us form in But imagecreatetruecolor is not defined what can i do


    Check GD support ,

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer