« File uploading with PHPPut watermark on images using PHP »

Captcha image verification Posted in PHP Tutorials | 232 Comments
A good way to avoid automatic form submissions when creating a web form is to add some kind of verification. One of the best ways is to use an image verification, called also captcha. What it does is to dynamically create an image with a random string displayed on it. Then visitor is asked to type that string in a text field and once the form is submitted it checks if the string on the image matches the one inputted by the user. Because there is no easy way to read a text from an image (image recognition) this is a good way to protect your web forms from spammers.
For doing this CAPTCHA I would suggest using a session variable where you store the string generated and displayed on that dynamically generated image.

$text = rand(10000,99999);
$_SESSION["vercode"] = $text;
$height = 25;
$width = 65;

$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;

imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);

Save this code in a file called captcha.php. What this script does is to generate a random number from 10000 to 99999 and then assign it to $_SESSION['vercode']. Then it generates a 25x65 pixels image with black background and white text using size 14. So if you upload that captcha.php file on your web site and open http://www.site.com/captcha.php you will see an image displaying random integer. You will receive a new random integer every time you refresh that page.

Next we need to create our web form.

<form action="submit.php" method="post"> 
Comment: <textarea name="coment"></textarea><br>
Enter Code <img src="captcha.php"><input type="text" name="vercode" /><br>
<input type="submit" name="Submit" value="Submit" />

Above code will create a form with a single textarea box, randomly generated image using the captcha.php script and a text field where you will have to enter the verification code.

All we have to do now is to make the submit.php script which will check if the verification code you enter matches the one that has been randomly generated.

if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='') {
echo '<strong>Incorrect verification code.</strong><br>';
} else {
// add form data processing code here
echo '<strong>Verification successful.</strong><br>';

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your experience with millions of other webmasters visiting our website. Contact us for more information how to become a contributor.

232 Replies to "Captcha image verification"

mark November 2, 2010 at 1:52 pm | Reply


Hi, I have already made a good looking contact form and it works via a formtoemail.php file, just woundering how would i add this captcha code to my existing contact form so i dont get spam thanks for your help
Luke Williams November 1, 2010 at 6:57 pm | Reply


it comes up with a error and i cant save it
Megh September 23, 2010 at 11:31 am | Reply


hiii,my captcha.php generates image perfectly in my browser bt when i insert the web form into the same file then i dont get the image infact get many charaters like in unicode form,can u solve the problem for me
Tamilselvan June 14, 2010 at 9:45 pm | Reply


Hi hello,
Generating the captcha image is success but if i want to store that in my db which type of column will i use like int, vatchar, char, text etc. i am new to php please help
Blomberg May 25, 2010 at 8:58 am | Reply


Nice to hear it works. Not sure what is wrong. Can not get a positiv result. Have also a problem when I use hmtl submit special with IE ver 6 & 8 tested. The php code just disappear. I use a little special domainname xn--myname-oka.com. So maybe that is my problem and not the code here.
I just some new white hair :-(
July May 24, 2010 at 5:27 pm | Reply


I can see is working well,can you create without including an e-mail, almost that I have seen include an e-mail
Blomberg May 16, 2010 at 6:15 pm | Reply


What to do???
Even when I write the right verification code the result is: Incorrect verification code
constantin May 3, 2010 at 6:53 pm | Reply


i already sent it to php.net too..

this is respons for
adam at worldwrestlingmania dot cjb dot net
06-Dec-2009 04:35(here http://php.net/manual/en/function.imagettftext.php)

and for all that's using captcha to prevent send information in a form using a robot.

People you don't need captcha!!!! There is another convenient method , to protect a website for spamming and is much simple:

Let's consider the 1st page(with the form) and let's say the second ... index.php and receiver.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
echo('this is the form`s page');
?><FORM METHOD=POST ACTION="receiver.php">
<INPUT TYPE="text" NAME="data"> <INPUT TYPE="submit" VALUE="send!" NAME="send"><BR>
A form without captcha!!!

function protectform(){

if (isset($_SERVER["HTTP_REFERER"]))
if (!$noterror )
if ($gethost['host']!==$servername)

if ($pimp){
die('Go away hacker!');

if(isset($_REQUEST['send'])and (trim($_REQUEST['data'])!='') ) echo('We already send to this page this value: '.$_REQUEST['data'].'<br>'); else echo('Please try to fill something in that form!');
?><A HREF="index.php">Return to my form</A>

how to probe it?
well let's say you already upload it on
www.example.com/myfolder/ index.php and receiver.php

so try to digit

now fill the form's value...and click send.
now is redirected to receiver.php and you see the right value.

Let's probe the vulnerability of the script:
digit again
now when you see the form press File/Save as from the browser's menu and save it on desktop like index.html

now try to open with notepad to edit it and change this line:
<FORM METHOD=POST ACTION="receiver.php">

to something like this:
<FORM METHOD=POST ACTION="http://www.example.com/myfolder/receiver.php">

now save it and double click it from desktop.
well what you see when you already fill that text form and you send the data to www.example.com/myfolder/ ?

(For php beginners:www.example.com can be www.banana.com too , i don't know where you will probe this software)

to all people who said :"php is unsecure" i respond with :
I am writing scripts from 1992, my opinion like expert is : php rooooooooolez!!! people if you don't know how to write scripts in php try php.net to learn something. me,Constantin
jamie April 15, 2010 at 3:57 am | Reply


hi guys i have html form page that requires verification tat an email address an valid name were entered, how much to ad your script to it, what would you charge, its contact us form.
Someone? March 29, 2010 at 3:30 am | Reply


Add header("Content-type: image/jpeg"); to the start of the code, and also imagedestroy($image_p); at the end of the code. The first fixes the jibberish problem and the second prevents memory leakage. Also, you can change the type to png quite easily, and I recommend it as jpeg is a sh!t quality image format.

You need GD for this. Ubuntu server install: sudo apt-get install php5-gd then sudo /etc/init.d/apache2 restart and tada! the php page will show jibberish, which is actually a jpeg. Use the img tag like it shows, and it works great.

Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~