Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

How to create a CAPTCHA image check in PHP

From Wiki
Jump to: navigation, search
Article Metadata
Created: Maveric (09 Mar 2012)
Last edited: hamishwillee (31 Jul 2012)

This article explains how to create a CAPTCHA image check in PHP



CAPTCHA is an acronym of the following sentence "Telling Humans and Computers Apart Automatically". A CAPTCHA is a program that can generate and grade tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown below, but current computer programs can't: The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University. At the time, they developed the first CAPTCHA to be used by Yahoo.

Reasons why websites would use a CAPTCHA:

In this article we will demonstrate on how to create a CAPTCHA using the PHP and it's graphics library called GD to generate the image.

-Preventing Comment Spam in Blogs. Most bloggers are familiar with programs that submit bogus comments, usually for the purpose of raising search engine ranks of some website (e.g., "buy penny stocks here"). This is called comment spam. By using a CAPTCHA, only humans can enter comments on a blog. There is no need to make users sign up before they enter a comment, and no legitimate comments are ever lost!

- Protecting Website Registration. Several companies (Yahoo!, Microsoft, etc.) offer free email services. Up until a few years ago, most of these services suffered from a specific type of attack: "bots" that would sign up for thousands of email accounts every minute. The solution to this problem was to use CAPTCHAs to ensure that only humans obtain free accounts. In general, free services should be protected with a CAPTCHA in order to prevent abuse by automated programs.

-Online Polls. In November 1999, released an online poll asking which was the best graduate school in computer science (a dangerous question to ask over the web!). As is the case with most online polls, IP addresses of voters were recorded in order to prevent single users from voting more than once. However, students at Carnegie Mellon found a way to stuff the ballots using programs that voted for CMU thousands of times. CMU's score started growing rapidly. The next day, students at MIT wrote their own program and the poll became a contest between voting "bots." MIT finished with 21,156 votes, Carnegie Mellon with 21,032 and every other school with less than 1,000. Can the result of any online poll be trusted? Not unless the poll ensures that only humans can vote.

-Preventing Dictionary Attacks. CAPTCHAs can also be used to prevent dictionary attacks in password systems. The idea is simple: prevent a computer from being able to iterate through the entire space of passwords by requiring it to solve a CAPTCHA after a certain number of unsuccessful logins.

-Search Engine Bots. It is sometimes desirable to keep webpages unindexed to prevent others from finding them easily. There is an html tag to prevent search engine bots from reading web pages. The tag, however, doesn't guarantee that bots won't read a web page; it only serves to say "no bots, please." Search engine bots, since they usually belong to large companies, respect web pages that don't want to allow them in. However, in order to truly guarantee that bots won't enter a web site, CAPTCHAs are needed.

-Worms and Spam. CAPTCHAs also offer a plausible solution against email worms and spam: "I will only accept an email if I know there is a human behind the other computer." A few companies are already marketing this idea.


-PHP installed and enabled on a local or remote web server -GD library enabled (if not by default). PHP comes with the library automaticly installed. -A True Type font file of your choise (e.g. if you are using WAMP in Windows environment, you can select a ttf file from the Windows system directory, and make a copy of it to another name.

Example code

The example will consist of the following phases:

- Creating the CAPTHA generating mechanism

--Converting text to image

--Adding "noise" to the image

- Performing CAPTCHA image validation against the user text input

- Creating an input form to be used on a web page complementing all the phases


This file will contain the needed functionality to create the CAPTCHA. The important used PHP functions are: imagecreate(), imagecolorallocate(), imageline(), imagettftext(). The imagecreate() function will convert text to an JPEG image, the imagecolorallocate() will set the bg and fg colors of the outputted image, the imageline() function will create lines on the image, and the imagettftext() function will take the ttf font supplied into use. First step will be to initiate a new session with session_start(), and then to change the outputted page content type to support the image format with setting the header content type to image/jpeg. The session variable will be set after this, followed by local variables for the font size, image width and height so that they can be changed and adjusted at will. To create the CAPTCHA image we first need to create an image with the imagecreate() function. For the image we will then set the background color and the foreground color with the imagecolorallocate() function (value in RGB format). For text outputted in the image frame we will set the colors with imagecolorallocate also, by saving it to the $text_color variable that will be used later on. The imageline() function is used to create random lines over the image to make it more difficult to read by machine, being still human-readable. For that we have created four variables and given them random values ($x1,$x2,$y1,$y2). After this we will issue the imageline() function by passing the $image variable and the randomly created values (30 lines) as overlay for the image, with the text color of $text_color we had set earlier. Finally the imagejpeg() function will create the actual CAPTCHA graphic onscreen with the passed $image as content.

header('Content-type: image/jpeg');
$text = $_SESSION['secure'];
$font_size = 30;
$image_width = 110;
$image_height = 40;
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
for($x=1; $x<=30; $x++) {
$x1 = rand(1, 100);
$y1 = rand(1, 100);
$x2 = rand(1, 100);
$y2 = rand(1, 100);
imageline($image, $x1, $y1, $x2, $y2, $text_color);
imagettftext($image,$font_size, 0, 15, 30, $text_color, 'font.ttf', $text);
// creates the output image to the web page


The index.php will by initiating a new session, create a four figure random number to be used as the CAPTCHA. The amount of numbers is ofcourse user definable. The index.php starts, as with the captcha.php, with a session_start() function. For the $_SESSION variable we will give te content of the randomly generated number and refer this to 'secure', connected to the captcha.php part.

<img src="captcha.php" /><br>
echo $_SESSION['secure']

The img src will get the out put of the result of running the captcha.php, which is an image of JPEG format. This image will be our CAPTCHA image, four digit number with the overlaying lines on it and using the TTF font we have issued. For debugging purposes, we are echoing the $_SESSION content, so that the whole process can be visually verified. Every refresh will produce a new image.

User input form

We will now modify the index.php so, that the user can submit a response for the CAPTCHA challenge issued. We will check with the isset() function if the user has already submitted the form, if then we do not yet want to create a new random number. If the user response to the challenge was correct, we will out put a text "Correct response"; this for debugging. In your solution you could just e.g. show that the form was submitted correctly or let the user to see a logged in message, or just to redirect the user to a new web page etc.

if (!isset($_POST['secure'])) {
$_SESSION['secure'] = rand(1000,9999);
if ($_SESSION['secure']==$_POST['secure']) {
echo 'CAPTCHA OK.';
} else {
echo 'Wrong CAPTCHA. Try again.';
$_SESSION['secure'] = rand(1000,9999)
<img src="generate.php" /><br>
<form action="index.php" method="POST">
Type the value you see: <input type="text" size="6" name="secure"> <input type="submit" value="Submit">

If the challenge was wrong, a new CAPTCHA is automatically generated.

Tested with

PHP 5.4

This page was last modified on 31 July 2012, at 07:26.
477 page views in the last 30 days.