on Apr 17th, 2008Generating CAPTCHA Image Using PHP

The CAPTCHA concept is very useful to prevent automated registration. If you have enabled gd library, you can create a captcha code for your registration form using PHP.

Consider the following parts of code, name the file as "captcha.php"

session_start();

if(isset($_SESSION[‘captcha’]))
{
unset(
$_SESSION[‘captcha’]);
}

The above code will start session and clear the old captcha’s session value if it set.

$num_chars 5//number of characters for captcha image
$characters array_merge(range(0,9),range(‘A’,‘Z’),range(‘a’,‘z’)); //creating combination of numbers & alphabets
shuffle($characters); //shuffling the characters

The above part of code describes the number of captcha characters and total available characters, here I am using all the lower and upper case alphabets and all numerics.
//getting the required random 5 characters
$captcha_text "";
for(
$i=0;$i<$num_chars;$i++)
{
$captcha_text .= $characters[rand(0,count($characters)-1)];
}

$_SESSION[‘captcha’] = $captcha_text// assigning the text into session

This part of code generated the required captcha code in a random manner from the available character array, also It assigns the value to session variable.

header("Content-type: image/png"); // setting the content type as png
$captcha_image imagecreatetruecolor(14030);

$captcha_background imagecolorallocate($captcha_image225238221); //setting captcha background colour
$captcha_text_colour imagecolorallocate($captcha_image589447); //setting cpatcha text colour

imagefilledrectangle($captcha_image0014029$captcha_background); //creating the rectangle

$font ‘Arial.ttf’//setting the font path

imagettftext($captcha_image2001121$captcha_text_colour$font$captcha_text);
imagepng($captcha_image);
imagedestroy($captcha_image);

The remaining code will draw the image.

How to use this captcha?

It’s simple, in your registration form put this part of code:

<img src="captcha.php">

Then you can put a text box to enter the captcha value, and then you can compare the entered captcha value with the assigned captcha session value.

 

2 Responses to “Generating CAPTCHA Image Using PHP”

  1. Soumyaon 07 Jun 2008 at 7:07 am

    how to shuffle the captcha code?as shown in this site

  2. phpbitson 08 Jun 2008 at 1:28 pm

    Call the following js function while clicking on the image:

    function changeCaptcha()
    {
    ran = Math.floor(Math.random()*10000);
    document.getElementById('captcha').src = 'captcha.php?rand='+ran;
    }
    

    and change the image tag as:

    <img src=”captcha.php” id=”captcha” onclick=”javascript:changeCaptcha();”>

Trackback URI | Comments RSS

Leave a Reply