Duminda Chamara

Wednesday, February 20, 2013

Create captcha image in php

How to create CAPTCHA image in PHP?

This article explains you how to create captcha image using PHP programming language

What is a captcha image?

CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. Captcha image is small image (jpg, png, or gif) with a random tiny text that use to stop automated form submission. Generally there can be characters,numbers, or combination of characters and numbers on the captcha validation image. The text on the captcha image is difficult to read at once. You have to see it carefully, to identify characters represent on the image. There are hundreds of fonts use to make captcha verification images. Also there can be irregular lines on the image. All those things make it difficult to read the text on the image. Only a human being can read and understand the text on the captcha image. No other easy method to read the verification code. Usually there are 4 to 16 characters on a captcha image. When the number of characters increased, the text is divide in to two words. So the user have to clearly identify those words.

Demo: Create CAPTCHA validation image

Why we use captcha verification codes/images?

You may also experience with automated form submission. Automated form submission means submit a web form using a computer program. As an example you can use Curl to submit web forms automatically. This may cause waste server resources, exceed CPU usage and hosting provider may suspend your hosting account. Using robot programs can fill your database with garbage. This is very annoying. So computer engineers purpose the solution of captcha images. Before you submit the form you must prove that you are a real human. Captcha images are difficult to read using robot programs. Only humans can do.

The text on the captcha image is changing randomly. If you failed to enter correct code you may ask to enter a new captcha code. Likewise verification code changes every time that you submit the form. If you fail to enter the captcha code two or three times, some captcha programs ask you to enter complex verification codes.

How captcha image works?

This is simple. When you request the from from the web server, at the same time it generates a session variable that contain the captcha text. There is a script that use to generate a image including the captcha string. It makes the text difficult to read. This can be achieve using several steps.

Captcha Image Verification Process
  • Change the font style randomly (Usually captcha fonts are difficult to read at once).
  • Change the font size randomly.
  • Change captcha text randomly.
  • Add lines, dots to the image to make it difficult to read (distort the image).
  • Produce combination of simple/capital letters with numbers.
Using above methods you can generate more reliable captcha codes. After you fill the web form, additionally you have a challenge to enter the correct captcha code. If all OK you can submit the form. At the server side first task is match the generated captcha code with the entered captcha code. Before process the request, you need to pass the captcha verification test. Once you have entered the captcha code correctly, computer recognize you as a real human and execute the rest of the program. If you failed to pass the verification test, you may again ask to enter a new captcha code. So you need to enter correct captcha code to process your request.

Is it possible to break/crack captcha images?

We can't 100% guarantee that captcha codes can stop spams completely. But it can effectively stop spams. Today there are many computer character recognition programs are developed to read captcha images. Those programs can identify characters in to some extent. Also they have proven such programs can pass the captcha test. But automated computer programs can't recognize all kind of verification codes. So the challenge is creating creative complex captcha images that hard to break.

Advantages of using captcha verification images?

  1. Stop automated form submission.
  2. Stop several kinds of spams (E-mail, registration forms, forum/blog comments, etc.).
  3. Save server resources such as bandwidth, storage, memory and CPU usage.
  4. Help to read old books and digitize them. 
  5. Preventing dictionary attacks.
  6. prevent overloading web servers from spammers.
  7. Prevent automated attacks.

Usage of CAPTCHA images?

  • When creating e-mail accounts. (Gmial, Yahoo, MSN e-mail programs ask to proof you as human using captcha codes).
  • When logging to email accounts.
  • Blog, forum comment submission.
  • In any kind of online user registration forms.
  • When downloading files from file sharing sites.
  • Any kind of user login forms.
  • Online Polls.
  • Stop sending automated queries to search engines.
  • To stop any kind of spam.

1. How to create captcha image in PHP?

Following code explains you the process of generating captcha verification image using php. You need to enable php gd library before you start image manipulation. Edit your php.ini file to enable gd library. Changing image font is also important in creating captcha codes. In this example you can use array of fonts to generate captcha code. Add some font files to a folder and use those files randomly to display the captcha text. Before you execute the program make sure all font files included in the font directory. Also you can add random colors for the generated captcha code. Also you can change text alignment. Finally you can add some random lines across the image to make it difficult to break by using robot programs. Likewise you can generate more creative random image.


$width = 120;
$height = 40;
$font_size = mt_rand(25,31);


$image = imagecreate($width,$height);

$background_color = imagecolorallocate($image,0,0,0);
$font_color = imagecolorallocate($image,mt_rand(200,255),mt_rand(80,255),mt_rand(100,200));
$text = '';
$font = 'fonts/'.$fonts[mt_rand(0,count($fonts)-1)];

$_SESSION['captcha_code'] = $text;



header("Content-Type: image/png");

function generate_random_text($length,$method=1){
case 1:{
$str.=(chr(mt_rand(97,122)));//Lower Case Characters
case 2:{
$str.=(chr(mt_rand(65,90)));//Upper Case Characters
case 3:{
$str.=chr(mt_rand(48,57));//Numbers 0 - 9
return $str;


Above code will generate a small image which contains a random combination of lower case and upper case letters and numbers. It is very easy to create captcha validation code using php. Copy and above code to a file and save it as captcha.php

2. How to add captcha image to a website?

You have already create your captcha image. Next step is adding that captcha code to your website. Suppose that you need to add a captcha code for your contact us page, You have to insert image tag and give the captcha image script file name as image path. Then you have to provide a text box to enter the captcha code. Also you need to give an option to user to reload the captcha image. Because some captcha codes are difficult to read. You can use a simple javascript code to reload the verification image. Most important is append a random number to the end of the file name. Because it stops caching the captcha image.

$message = isset($_REQUEST['message'])?$_REQUEST['message']:'';
$info = 'Thank You';
$info = 'Please enter correct captcha code';
<meta charset="utf-8">
<script type="text/javascript">
function reload_captcha(){

<form action="contact-us-save.php" method="post" name="contact_us" id="contact_us">
<table border="0">
<? if(isset($info)){?>
<td colspan="3" align="center"><?=$info?></td>
<? } ?>
<td>First Name</td>
<td><label for="first_name"></label>
<input name="first_name" type="text" class="text_box" id="first_name"></td>
<td>Last Name</td>
<td><label for="last_name"></label>
<input name="last_name" type="text" class="text_box" id="last_name"></td>
<td>Email Address</td>
<td><label for="email"></label>
<input name="email" type="text" class="text_box" id="email">
<td><label for="message"></label>
<textarea name="message" cols="30" rows="5" class="text_box" id="message"></textarea></td>
<td><img id="captcha_image" alt="Captcha Verification Image" src="captcha.php?r=<?=mt_rand(100,1000)?>" width="120" height="40" border="1">&nbsp;<a href="javascript:void(0);" onClick="javascript:reload_captcha();">reload</a></td>
<td>Verification Code</td>
<td><label for="verification_code"></label><input name="verification_code" type="text" class="text_box" id="verification_code">
<td><input name="btn_save" type="submit" class="btn_green_submit" id="btn_save" value="Submit"></td>

Copy and paste above code and save it as contact-us.php

3. How to check and validate captcha code in server side?

Now you have created your web form that you need to place the captcha validation. Next step is validate user inputs. As you already know when user request the web form, he gets a new captcha code every time. At the captcha image generation process, it create a session variable with generated captcha code; which display on the image. What you have to do is check user entered captcha code with session variable. If user input matches with session value, you can execute rest of the code. Refer bellow example.


$verification_code = isset($_POST['verification_code'])?$_POST['verification_code']:'';


$mysqli = new mysqli('localhost','root','1234','contacts');

if ($mysqli->connect_errno) {
$stmt = $mysqli->prepare("INSERT INTO contact_us(first_name,last_name,email,message) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $_POST['first_name'],$_POST['last_name'],$_POST['email'],$_POST['message']);
header("Location: contact-us.php?message=success");
header("Location: contact-us.php?message=captcha_error");


Copy and paste above code and save it as contact-us-save.php. Then open contact-us.php to test the example. Please note that you have created font folder and change the font names accurately. Hope you got it.

* Please note you have to implement validations for first name, last name, email address. This sample code shows a simple captcha verification program. Please modify it to meet your requirements.


Anonymous said...

Good article....

Unknown said...

Grate tutorial. Easy to understand. Thanks for sharing.

Unknown said...

Nice post.. all information and program explanation are very clear so easy to understand..

php training | php training in chennai

Juliana Kho said...

Thank you for your information, please visit: