Taking tutorial submissions! Please email them to dave[AT]icemelon[DOT]com for review. Thanks!

Latest Tutorials
IceMelon IM: Add IM Functionality to phpBB [Misc] Want to add site-wide member IM to your phpBB community? Sure you do. Simple step-by-step instructions inside.

IceMelon IM: Add IM Functionality to vBulletin [Misc] Want to add site-wide member IM to your vBulletin community? Simple step-by-step instructions inside.

Crawl Your Site for PageRanks [PHP] So you know your site has a PageRank of 8. What about the PRs of all the inner pages? This tutorial will teach how you to automate the process of grabbing all these PRs.

Create CAPTCHA images [PHP] Worried about bots? Then create CAPTCHA images to prevent bots from taking advantage of your site.

Convert SHN and FLAC files to MP3 [Misc] Low on disk space and have an insensitive ear? Here are some steps to converting SHN and FLAC files to MP3 format.

[View All]

Become a sponsor for $15/month. Link is sitewide - PR5 homepage, 20+ PR4 pages, 90+ PR3 pages. Email dave[AT]icemelon[D0T]c0m.

Awesome Tutorials

Create CAPTCHA images
By dave

First off, you may be wondering what a CAPTCHA image is. Here's a brief synopsis from Wikipedia:

A captcha (an acronym for "completely automated public Turing test to tell computers and humans apart") is a type of challenge-response test used in computing to determine whether or not the user is human.

Captchas are used to prevent bots from using various types of computing services. Applications include preventing bots from taking part in online polls, registering for free email accounts (which may then be used to send spam), and, more recently, preventing bot-generated spam by requiring that the (unrecognized) sender pass a captcha test before the email message is delivered.

That not clear enough? Here's an example:


The one where will generate in this tutorial will look like this (unfortunately, not as cool or elegant):

Generating the random string
The first thing to figure out is how to generate a random string. We can accomplish this by creating random number (rand) and then by plugging that value into a built-in PHP hash function (md5). Here's the code:
$enc_str = rand(1,100);
$random_string = substr(md5('icemelondawg'.$enc_str), 2,8);
Note the following...
  • to make our string really random, we append our random number to the impossible-to-guess-string "icemelondawg."
  • using the substr function, we can reduce our string length down to 8 characters. (The 2 you see in the code refers to the starting index — i.e. to start from the beginning, replace 2 with 0. I like to use a non-zero starting index as a means of further encryption.)

    Generating the image
    To do this, you will need have the GD module installed on your server. If you don't have it, you can grab it here: [http://www.boutell.com/gd/] (More details in my Dynamic Images tutorial.)

    What we want to accomplish here is to overlay our random 8-character string over a background image. The point of that is so that... when looking at the image, it would be easy for a human to decipher the string, but not so easy for a robot. (Stupid robots.) Here is the background image we will be using:
    [http://www.icemelon.com/tutorials/stuff/imagecode_bg.png]

    And, here's the code:
    Header ("Content-type: image/png");

    $enc_str = rand(1,100);
    $random_string = substr(md5('icemelondawg'.$enc_str), 2,8);

    $img_handle = imageCreateFromPNG("imagecode_bg.png");
    $color = ImageColorAllocate ($img_handle, 450, 450, 450);
    ImageString ($img_handle, 5, 20, 13,  $enc, $color);
    ImagePng ($img_handle);
    ImageDestroy ($img_handle);

    Putting things together & changing things around
    Now, our objective is to have a form for the user to enter the 8-character string into, so that we can verify whether the user has entered in the string correctly. Here's a script in action:
    [http://www.icemelon.com/tutorials/stuff/imagecode.php]
    (Test it out, because we will be going over it below.)

    Here's the code for the above script (imagecode.php) in its entirety:
    <?
    // image
    if(isset($_GET['img'])) {

        Header ("Content-type: image/png");
        $img_handle = imageCreateFromPNG("imagecode_bg.png");
        $color = ImageColorAllocate ($img_handle, 450, 450, 450);
        $enc = substr(md5('icemelondawg'.$_GET['enc']), 2,8);
        ImageString ($img_handle, 5, 20, 13,  $enc, $color);
        ImagePng ($img_handle);
        ImageDestroy ($img_handle);

    // check code
    } elseif(isset($_POST['register'])) {

        session_start();
        echo '<h2> ';
        if($_POST['enc']==$_SESSION['enc_img'])
            echo 'Correct. ';
        else
            echo 'Incorrect. ';
        echo '</h2> ';

    // form
    } else {

        session_start();
        // generate random encryption string
        $enc_str = rand(1,100);
        $_SESSION['enc_img'] = substr(md5('icemelondawg'.$enc_str), 2,8);

        // registration form
        echo "
            <h2>Are you Game?</h2>
            
            <form method=POST action=imagecode.php>
            <p><img src=\"imagecode.php?img&enc=$enc_str\">
            <br>Copy the 8-digit code above:
            <br><input type=text name=enc>
            <input type=submit name=register value='verify!'>
            </form>
            ";
    }
    ?>

    (Aside: I put all the code into one script. However, for your needs, it would probably best to split up the code into separate files.)

    Note that we need to use the CAPTCHA string three times:
  • First time... when we initially generate it on the form page.
  • Second time... when generating the CAPTCHA image.
  • Third time... after form submission, to check our visitor's input against the actual code.

    However, we can only generate this code once using the random number generator method! (Why? Well, if we generate it more than once, we will have more than one random numbers and ergo more than one 8-character codes.) Therefore, (referring to the code above) we only call rand once. Using the random number, we generate our code (with md5 and substr) and store this code into a SESSION variable: $_SESSION['enc_img'].

    We then pass our random number ($enc_str) to the image-generation part of our script. (This is done via the source URL of the image.) This image-generation part of the script will use the random number to re-create the 8-digit code. (Why not pass the entire code to this part of our script? Well, we don't want our 8-digit code to appear in any part of our HTML. This is a because a robot can easily parse the HTML to extract the code.)

    Finally, after the user inputs and submits the CAPTCHA code, we check the POST variable against the SESSION variable. (Aside: remember, when using sessions, you need to started the sessions with session_start at the top of the script. Do not start a session in the image-generation part of the script. The script will throw header output errors.)

    Well, that's a wrap. Feel free to use my background image for the CAPTCHA code, but please do not link directly to it on my server. Thanks.
  • P.S. Check out my new site TheManWhoSoldtheWeb.com, where I publish guides and scripts on Internet Marketing and SEO. Here is a limited time freebie: the Rapid Google Indexer.


    » Bookmark this Tutorial
    » Bookmark IceMelon
    Icemelon -- Create CAPTCHA images -- PHP, CSS, Javascript Tutorials, & More!
      © 2005-2010 Icemelon.com   Email: dave[AT]icemelon[D0T]c0m