PHP Tutorial : How to create a captcha image

Hi,
Are you tired of receiving spam messages from your contact forms or unwanted posts, robot accounts on your membership website? If yes, the solution is to create a php security image called captcha. That’s the best solution to secure your web forms, etc. For creating a captcha security code you need to have GD-library installed and active on your webhost, but, most of the shared webhosts have this library installed. Here is the captcha code :

<?php
//The first step is to start a php session calling the special function
session_start();
//The seccond step is to generate a string randomly using rand function
//I'll choose to get a random number 6 numbers in length
$randomcode = rand(0, 999999);
//Now we need a background image to write the random number to it
$captchafromimage = imagecreatefrompng("captcha.png");
//Setting font color
$color = ImageColorAllocate ($captchafromimage, 50, 50, 50);
//Ta da, here we are, writing the random generated code to the image
imagestring($captchafromimage, 6, 50, 2, $randomcode, $color);
//Now the random number is coded into md5 secure format
//and stored it into a session name to be able to validate
//it in the future
$_SESSION['randomcode'] = md5($randomcode);
//Set up headers
header("Content-type: image/png");
//Finally, let's show up the captcha image generated
imagepng($captchafromimage);
?>

You will need a background PNG image which you can download here (right click -> Save as)
captcha image
Here is the captcha result :
php captcha

This entry was posted in Usefull PHP and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>