How to Make Your Own PHP Captcha Generator

ManzZup's Avatar author of How to Make Your Own PHP Captcha Generator
This is an article on How to Make Your Own PHP Captcha Generator in PHP.
In this article we will create file based simple yet successful captcha generator.

3 Major Anti-spamming techniques used?
  1. Mathematical Operation like Random number + Random Number = -> The user must specify the answer
  2. Random word -> User must type the word
  3. Random question -> Obvious one which the user should answer correctly [ex: Are you human?]
How Captcha works?
  1. The captcha generator generates an IMAGE with the question and then put up a session variable storing the value.
  2. User input though an input box.
  3. Using php POST, we compare the session variable data with the user input and tell whether its a bot or human. Its coding time

The Code

  1. First let's write the php script which generates the captcha image. We use the simple header-content change technique, from which we can easily bring up an image from a given text.
    captcha.php

    PHP Code:
    <?php
    //This should be the first line as in the rule book :D
    session_start();
    //These variables store the Question and the answer
    $ques "";
    $ans "";
    //This is the MAJOR array, this holds all the random things, like the question you need to ask. You can add up new ones easily
    $words = array(
            
    => array("Num" => "Num"),
            
    => array("Are you human?" => "yes"),
            
    => array("Type 'one' " => "one"),
            
    => array("Type 'test' " => "test"),
            
    => array("AxHGA" => "AxHGA"),
            
    => array("zontek" => "zontek"),
            
    => array("12terd " => "12terd")
        );
        
    //Now we need to pic up a random question, array_rand is the perfect thing to this
        
    $r array_rand($words);
        
    //Then we check about what we have in the select array
        
    switch(key($words[$r])){
            
    //If we have the "NUM" selected, that is a special one
            //Num means the user will be prompted to doa simple addition like 5+6
            
    case "Num":
                
    //Pretty basic stuff, generate 2 random numbers and tell the user to put the addition
                
    $i rand(1,10);
                
    $j rand(1,10);
                
    $ans $i+$j;
                
    $ques "$i + $j = ";
                break;
            default:
                
    //If not a number, ask the user a question or ask him to type a word
                
    $key key($words[$r]);
                
    $ques $key;
                
    $ans $words[$r][$key];
                break;
        }

    //NOW we put up the answer to the session variable
    $_SESSION['cap'] = strtolower($ans);
    //This would change the content type, or in english this would tell the browser that
    //what ever retuened by this script is an image
    header('Content-Type: image/png');

    //Following code is to generate the image from the test
    //We first specify colour ranges, you can refer to the php manaul for more
    $img imagecreatetruecolor(250,30);
    //In the above code, the image size is set to 250x30
    $white imagecolorallocate($img,255,255,255);
    $grey imagecolorallocate($img,128,128,128);
    $black imagecolorallocate($img,0,0,0);
    //Filling the rectangle with white as we need black text on white
    imagefilledrectangle($img,0,0,399,29$white);
    $text $ques;
    //THE below code is CRITICAL. This is the palce where we tell which font to use.
    //Choose any ttf you like and name it as font.ttf or change the following code, make sue
    //you put the path to the file correctly [i used STENCIL so that parsers will find it hard to detect]
    $font "./font.ttf";
    imagettftext($img,20,0,11,21,$grey,$font,$text);
    imagettftext($img,20,0,10,20,$black,$font,$text);
    //Creating a PNG image, i use png cuz i <3 png [really its so small and efficient ;)]
    imagepng($img);
    //And then remove the memory parts once the output is given
    imagedestroy($img);
    ?>
  2. Haa that's all But you still need to know how to use the thing. We make our index.php and ask the user for the input as determine whether it is a spammer or not.

    index.php

    PHP Code:
    <?php
    session_start
    ();
    if(isset(
    $_POST['done'])){
        if(isset(
    $_SESSION['cap'])){
            
    //This is the code for comparing the user input against the session variable
            
    $cap $_POST['captcha'];
            if(
    $_SESSION['cap']==strtolower($cap)) echo "Okay you are human :)";
            else echo 
    "Off You go BOT / SPAMMER!!";
        }
    }
    ?>
    <html>
    <head>
    <title>Simple Captcha Script</title>
    </head>
    <body>
    <form action="index.php" method="post">
    <img src="captcha.php" align="absmiddle" />
    <!-- NOTE how the captcha.php is used as an image link, that's a whole new way to think -->
    <input type="text" size="20" name="captcha" /><br />
    <input type="submit" name="done" value="Login" />
    </form>
    </body>
    </html>
  3. Upload the stuff and make sure you have the following files in the same directory level : index.php captcha.php font.ttf


It's done, now you have your own little cpatcha script, well this is really basic, but once you know what to do you have no limits

Feel free to develop the code [and be kind enough to send me one as well ]

See the demo of the script here : http://expementa.freezoka.net/captcha/

That's all for today

See ya all with some other thing (no promises today though )
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You missed the font.ttf.
ManzZup's Avatar, Join Date: May 2009
Skilled contributor
i used the STENCIL.ttf as i have told
but you can use any true type font
nabila1230's Avatar
Banned
thank you brother to share such a great and help full sharing, keep it up
ManzZup's Avatar, Join Date: May 2009
Skilled contributor
pleasurez mine
donor's Avatar
Banned
Code:
<?php 
//Start the session so we can store what the security code actually is
session_start();

//Send a generated image to the browser 
create_image(); 
exit(); 

function create_image() 
{ 
    //Let's generate a totally random string using md5 
    $md5_hash = md5(rand(0,999)); 
    //We don't need a 32 character long string so we trim it down to 5 
    $security_code = substr($md5_hash, 15, 5); 

    //Set the session to store the security code
    $_SESSION["security_code"] = $security_code;

    //Set the image width and height 
    $width = 100; 
    $height = 20;  

    //Create the image resource 
    $image = ImageCreate($width, $height);  

    //We are making three colors, white, black and gray 
    $white = ImageColorAllocate($image, 255, 255, 255); 
    $black = ImageColorAllocate($image, 0, 0, 0); 
    $grey = ImageColorAllocate($image, 204, 204, 204); 

    //Make the background black 
    ImageFill($image, 0, 0, $black); 

    //Add randomly generated string in white to the image
    ImageString($image, 3, 30, 3, $security_code, $white); 

    //Throw in some lines to make it a little bit harder for any bots to break 
    ImageRectangle($image,0,0,$width-1,$height-1,$grey); 
    imageline($image, 0, $height/2, $width, $height/2, $grey); 
    imageline($image, $width/2, 0, $width/2, $height, $grey); 
 
    //Tell the browser what kind of file is come in 
    header("Content-Type: image/jpeg"); 

    //Output the newly created image in jpeg format 
    ImageJpeg($image); 
    
    //Free up resources
    ImageDestroy($image); 
} 
?>

Last edited by shabbir; 13Jan2012 at 13:03.. Reason: Code blocks