Simple PHP-GD captcha image

Simple PHP-GD captcha image

Thursday, June 21st, 2007 in PHP

If you need to secure a form from being automatically submitted by robots of by someone who wants to damage your server and/or scripts, it’s best that you use a captcha image.
For this one you’ll need PHP compiled with GD and the FreeType Support enabled (in order to use True Type fonts in your images).
OK, now let’s see what is this all about. We have two files. One is the file that holds the form, and the other one is the file that generates the captcha image.
The file that holds the form starts with the session_start() declaration and the setting of our security number.

1
2
3
4
5
<?
	session_start();
	// here you can perform all the checks you need on the user submited variables
        $_SESSION['security_number']=rand(10000,99999);
?>

After declaring our session variables, we can safely start our html document.

6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple capcha image</title>
</head>
 
<body>
This is our captcha image. In order for this to work, your server must have<br />
GD Libraries installed with the ttftext extension activated.<br />
<img src="image.php" alt="well, this is our captcha image" />
</body>
</html>

And that’s it. Now, we need to create our captcha image generator file. Let’s give this one a name, like image.php. It looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?
	session_start();
 
	$img=imagecreatefromjpeg("texture.jpg");
	$image_text = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
 
        $red=rand(100,255);
	$green=rand(100,255);
	$blue=rand(100,255);
 
	$text_color=imagecolorallocate($img,255-$red,255-$green,255-$blue);
 
	$text=imagettftext($img, 16, rand(-10,10), rand(10,30), rand(25,35), $text_color,
                 "fonts/courbd.ttf", $image_text);
 
	header("Content-type:image/jpeg");
	header("Content-Disposition:inline ; filename=secure.jpg");
	imagejpeg($img);
?>

After starting the session in order to make available our $_SESSION['security_number'] variable that we set up in the previous file, we start creating our captcha image.

All GD generated images start with the imagecreate() declaration. In this care I used imagecreatefromjpeg() function, which means I used an existing image for background.

After declaring the image we check if the $_SESSION['security_number'] variable holds some value and if it does, we output it in our captcha image otherwise we output ‘error’ instead of the number.

The $red, $green and $blue variables hold the RGB color code that the text will have. I used the rand() function in order to generate different colors each time the page is refreshed.

But just holding the color code in some variables won’t do the trick. What we need to do is assign the color to our image. We do that by using the imagecolorallocate() function. Every time we want to assign a color to a GD generated image we’ll need to use this function.

The imagettftext() function writes the actual text in our image at the position and using the angle we specify. For more information about this function, please refer to the PHP documentation available online here.

And finally, in order to tell the browser that we are sending an image, we need to set the proper headers and after that we output the resulting image using imagejpeg().

That’s all there is.

Was this useful? Show your support.

digg Simple PHP-GD captcha image

12 comments

  1. Thank you very much for this useful tutorial. I’m using it in my site!!! Thank again! :D

  2. You’re welcome. Hope it helps you. You might want to try the math captcha image also.

  3. Angelina says:

    Thanks we are really looking for this kind of utility to place our website for spam protection and we got all stuff that we needs thanks again…
    Regards.

  4. [...] I wrote a small tutorial about how to create a captcha image. After surfing the web today, I’ve found another idea. How about creating a captcha image [...]

  5. Cody Taylor says:

    For random spacing and coloring on each letter check http://codytaylor.org/?p=14213

  6. Achshar says:

    hello fellas
    i am a newbie and dont have much of coding experience….
    i got every thing but i dony find the form… like a text field…. and how to check if the value inserted in the text box is what the session has generated… i dwnloaded the script but index page only has the image not the form…
    so i guess it is not a ” working ” example…

  7. How you implement the form is your own choice. The purpose of this is to show a simple way to generate a captcha image. Try a google search, there are tons of tutorials on form processing.

  8. m7o says:

    Thanks a lot for the script, I added a bit to get better random numbers and letters and to have different angles and colors for them. I used a smaller jpg and changed the dimensions a bit, of course everyone can play with the numbers and the jpg size. And to make sure one won’t get an image from the browser cache add a unique or random string to the image url, for example like this:

    <?php
    echo “”;
    ?>

    The altered script:

    <?php

    session_start();
    srand((double)microtime()*1000000);
    $_SESSION['security_string']= substr(md5(uniqid()), 0, 5);
    $image_text = empty($_SESSION['security_string']) ? ‘error’ : $_SESSION['security_string'];
    $img=imagecreatefromjpeg(“texture.jpg”);
    $x = rand(5,10);
    for($n=0;$n

  9. m7o says:

    the code didn’t come though all they, it got gut off and the image tag got removed … too bad. Maybe I can post it somewhere else or send it to you.

  10. Shane says:

    Hi

    I downloaded and ran the script on a Windows server but was unsuccessful. I have GD installed (phpinfo(); stated everything was enabled); I also changed the php.ini file – changed ;extension=php_gd2.dll to extension=php_gd2.dll, restarted the server but still no joy. Any help would greatly appreciated.

    Thanks in advance, Shane

  11. Tiganus Razvan says:

    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

    index.php:
    ———————————————————————-

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

    ———————————————————————-

    receiver.php
    ———————————————————————-

    <?php
    //receiver.php
    function protectform(){
        
    if($_SERVER["REQUEST_METHOD"]!='GET'){

            
    $servername=$_SERVER["SERVER_NAME"];
            
    $noterror=true;
            
    if (isset($_SERVER["HTTP_REFERER"]))
                
    $gethost=Parse_url($_SERVER["HTTP_REFERER"]);
            
    else
                
    $noterror=false;
            
    $pimp=false;
            
    if (!$noterror )
                
    $pimp=true;
            
    if(isset($gethost))
                
    if    ($gethost['host']!==$servername)
                    
    $pimp=true;
            

        

            
    if ($pimp){
                
    //print_r($gethost);
                
    die('Go away hacker!');
            
    }

        
    }
    }
    protectform();
    if(isset($_REQUEST['send'])and (trim($_REQUEST['data'])!='') ) echo('We already send to this page this value:&nbsp;'.$_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
    http://www.example.com/myfolder/ index.php and receiver.php

    so try to digit
    http://www.example.com/myfolder/index.php

    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
    http://www.example.com/myfolder/index.php
    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 http://www.example.com/myfolder/ ?

    (For php beginners:www.example.com  can be http://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

Leave a comment