• home
  • forum
  • my
  • kt
  • download
  • PHP Captcha - Learn How to Make a Captcha in PHP

    Author: 2008-08-16 11:47:50 From:

    What is a CAPTCHA? CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart", which simply means that robots/scripts won't be able to submit a form, for example, it could prevent robots/scripts from automatically registering on your site or posting comments.

    To start this off, we will first create the script that will generate and output the actual image of the CAPTCHA. So create a file called captcha.php.

    captcha.php:
    <?php
    session_start
    ();
    $width 140;
    $height 70;
    $im imagecreate($width$height);
    $bg imagecolorallocate($im000);

    // generate random string
    $len 5;
    $chars 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $string '';
    for (
    $i 0$i $len$i++) {
        
    $pos rand(0strlen($chars)-1);
        
    $string .= $chars{$pos};
    }
    $_SESSION['captcha_code'] = md5($string);

    // grid
    $grid_color imagecolorallocate($im17500);
    $number_to_loop ceil($width 20);
    for(
    $i 0$i $number_to_loop$i++) {
        
    $x = ($i 1) * 20;
        
    imageline($im$x0$x$height$grid_color);
    }
    $number_to_loop ceil($height 10);
    for(
    $i 0$i $number_to_loop$i++) {
        
    $y = ($i 1) * 10;
        
    imageline($im0$y$width$y$grid_color);
    }

    // random lines
    $line_color imagecolorallocate($im13000);
    for(
    $i 0$i 30$i++) {
        
    $rand_x_1 rand(0$width 1);
        
    $rand_x_2 rand(0$width 1);
        
    $rand_y_1 rand(0$height 1);
        
    $rand_y_2 rand(0$height 1);
        
    imageline($im$rand_x_1$rand_y_1$rand_x_2$rand_y_2$line_color);
    }

    // write the text
    $text_color imagecolorallocate($im25500);
    $rand_x rand(0$width 50);
    $rand_y rand(0$height 15);
    imagestring($im10$rand_x$rand_y$string$text_color);


    header ("Content-type: image/png");
    imagepng($im);
    ?>




    Code Breakdown:

    session_start(); - We are going to be holding the actual value of the CAPTCHA in a $_SESSION variable, so we turn sessions on.
    $width = 140; - This is pretty self-explanatory, this is the width of the image.
    $height = 70; - Again, this is self-explanatory, this is the height of the image.
    $im = imagecreate($width, $height); - This creates the "handle" for the image, the image can now be accesssed with $im. It also sets width and height of the image to the values above.
    $bg = imagecolorallocate($im, 0, 0, 0); - This will set the background of the image. It uses RGB, the last 3 paramaters you see to this function accept the amount of red, green and blue, respectively. So in this case there is 0, 0, 0 which will give a background that is black.
    $len = 5; - This variable is the length of the random string that is being generated. The next few lines is just a simple way of generating a random string. If you want to make the string even more random, try adding more characters to the $char variable. (e.g. lowercase letters)
    $_SESSION['captcha_code'] = md5($string); - This assigns the encrypted random string to a $_SESSION variable so we can read the correct string and compare it with the string the user entered (which we will be doing later in this tutorial).
    $grid_color = imagecolorallocate($im, 175, 0, 0); - This is the color that the grid will be in the background (the background will be a grid with 20x10 squares), in this case it is a shade of red. The grid is one of the methods we will be using to mess up the image.
    $number_to_loop = ceil($width / 20); - This divides the width by 20 (since the squares in the grid will be 20px wide) and rounds it up. This tells us how many times to run the loop to make the lines along the X axis of the grid.
    imageline($im, $x, 0, $x, $height, $grid_color); - This plots the lines on the grid, along the X axis.
    $number_to_loop = ceil($height / 10); - This is the same as before except now we are dividing by 10 (since the squares in the grid will be 10px high).
    imageline($im, 0, $y, $width, $y, $grid_color); - Again, this plots the lines on the grid, but this time along the Y axis.
    $line_color = imagecolorallocate($im, 130, 0, 0); - This will be the color of the random lines all over the image. It will be a different shade of red, but more faded than the grid.
    for($i = 0; $i < 30; $i++) { - This will just loop 30 times. There is no particular reason for choosing 30, I just put in a random number. It simply just means that it will make 30 random lines. You could even make it so it does a random amount of random lines, it's all up to you.
    imageline($im, $rand_x_1, $rand_y_1, $rand_x_2, $rand_y_2, $line_color); - Using the random points generated directly above, it plots the line on the image.
    $text_color = imagecolorallocate($im, 255, 0, 0); - This will be the color of the text that the random string on the image will be in. In this case it is again, a different shade of red but this has the highest value for red, so it will be the clearest (over the grid and random lines).
    $rand_x = rand(0, $width - 50); - This will just give a random point along the X axis, it subtracts 50 so it doesn't generate a point that will cause the random string to run off the image. (I just guessed on how long the string could possibly be, it can probably only go about 43px)
    $rand_y = rand(0, $height - 15); - Again, this will just give a random point but along the Y axis, it subtracts 15 so it doesn't generate a point that will also make it run off the image.
    imagestring($im, 10, $rand_x, $rand_y, $string, $text_color); - Using the imagestring function it now writes the random string on the image.
    header ("Content-type: image/png"); - Change the headers so the browser knows it is viewing an image, and not the usual text/html.
    imagepng($im); - Now that everything is set, we can finally show our CAPTCHA.

    This next part gives a simple form to demonstrate what we just made. It doesn't have anything fancy in it, it just gets the result across, since this is a PHP tutorial, not an HTML/CSS tutorial.

    form.php
    <?php
    session_start
    ();
    if(isset(
    $_POST['submit'])) {
        if(isset(
    $_POST['captcha_code']) && isset($_SESSION['captcha_code'])) {
            if(
    md5($_POST['captcha_code']) == $_SESSION['captcha_code']) {
                echo 
    'Result: CAPTCHA code correct.<br />';
            }else{
                echo 
    'Result: CAPTCHA code incorrect.<br />';
            }
        }else{
            if(!isset(
    $_POST['captcha_code'])) {
                echo 
    'Result: No security code was entered.<br />';
            }
            if(!isset(
    $_SESSION['captcha_code'])) {
                echo 
    'Result: No CAPTCHA was viewed.<br />';
            }
        }
    }
    ?>
    <form method="POST">
    <img src="captcha.php" />
    <br />
    Enter the above text EXACTALY as it appears. Note: It is case sensitive<br />
    <input type="text" name="captcha_code" /> 
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    Code Breakdown:

    session_start(); - Just like before, we need to activate the sessions so we can access them.
    if(isset($_POST['submit'])) { - This is just simple check to see if the form was submitted (since we are gonna have the form and the code that validates it, all in one page).
    if(isset($_POST['captcha_code']) && isset($_SESSION['captcha_code'])) { - This checks if they actually submitted something and if they actually viewed our CAPTCHA we made earlier.
    if(md5($_POST['captcha_code']) == $_SESSION['captcha_code']) { - Here we compare our two variables to see if the user put in the correct value of the CAPTCHA. The rest of the PHP code is just error handling and is self-explanatory.
    <img src="captcha.php" /> - You may have noticed that we are using a script as an image, but since we changed the headers in our CAPTCHA, this will actually show a PNG image.

    That pretty much concludes this tutorial, keep in mind that the form is case-sensitive (which means "a" is not the same as "A"). Also, you may want to adjust the colors on the CAPTCHA, to customize it to your site (this tutorial used different shades of red).

    Here is what yours should look similar to:
     

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (19)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot