Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Securing Web Forms with Simple PHP-CAPTCHA

3.64/5 (8 votes)
15 Feb 2012CPOL3 min read 1   538  
How to implement a simple CAPTCHA system in a web form using PHP

Introduction

CAPTCHA is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart." CAPTCHA technology enables one to discern human requests from computer generated requests on the web, where such a distinction is often difficult. Simply stated: "Man can read; machines can’t!" This article illustrates how to implement a simple CAPTCHA interface for a web form.

Simple forms available over the web are always prone to attack by people who want to use your application for their own purposes. Many web sites use CAPTCHA to prevent bots from misusing their services. Among other things, CAPTCHA can be used to prevent bots from taking part in online polls, registering for free email accounts, and more recently, preventing bot-generated spam by requiring that the (unrecognized) sender pass a CAPTCHA test before the email message is delivered [implemented in Yahoo]. They have also been used to prevent people from using bots to assist with massive downloading of content from multimedia websites.

You have probably seen the CAPTCHA project in action at some of your Web destinations. Its principal tool is a randomly created image that contains a phrase displayed as a graphic image, rather than in computer-readable text on the rendered page. The form asks the user to provide the phrase. If the form post does not contain the correct phrase, you can safely assume either the human made a user error, or it wasn't a human at all.

Using the Code

Now it's time to put this code to work. A simple and often-used interface to implement this new security measure is the form on website. In this form you typically capture random numbers.

HTML
<form name="form1" method="post" action="form.php" ">
    <table width="342" align="center" cellspacing="0" bgcolor="#D4D0C8">
        <tr> 
            <td align="center">
                <img src="php_captcha.php">
            </td>
            <td align="center"> 
                Please enter the string shown in the image in the form.<br>
            </td>
            <td align="center">
                <input name="number" type="text">
            </td>
            <td>
                <input name="Submit" type="submit" value="Submit">
            </td> 
        </tr>
    </table>
</form>

The following code can be used to create random numbers and these numbers are embedded in an existing image file as follows. The first line initiates a session, which provides access to the user inputs. The second line will generate a random string $RandomStr which is trimmed to 5 characters in the third line. The imagecreatefromjpeg("img.jpg") function is used to create an image using an existing image file as back ground.

HTML
<?php
session_start();
$RandomStr = md5(microtime());
$ResultStr = substr($RandomStr,0,5);
$NewImage =imagecreatefromjpeg("img.jpg");
?>

We then modify the image with the following code, that specifies the colors to be used and generates several lines using the imageline() function. Next the imagestring() function is used to draw the trimmed random string, $ResultStr, horizontally onto the image and the string is also saved as a session variable to be checked later.

HTML
<?php
$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imageline($NewImage,1,1,40,40,$LineColor);
imageline($NewImage,1,100,60,0,$LineColor);
imagestring($NewImage, 5, 20, 10, $ResultStr, $TextColor); 
$_SESSION['key'] = $ResultStr;
?>

Finally the following lines are used to output the image to the browser to display the generated CAPTCHA image.

HTML
<?php
header("Content-type: image/jpeg");
imagejpeg($NewImage);
?>

The following is an example of code that could be used to validate the user input using the actual random number. The implementation of the if and else portions will depend upon the desired behavior of the application.

HTML
<?php
if(isset($_REQUEST['Submit'])){
    $key=substr($_SESSION['key'],0,5);
    $number = $_REQUEST['number'];
    if($number!=$key){
        echo ' Validation string not valid! Please try again!';
    }
    else
    {
        echo ' Your string is valid!';
    } 
}
?>


Conclusion

CAPTCHA can be a great way to limit the amount of successful, unwanted HTTP POST requests in your application. Since CAPTCHAs are by definition fully automated, no human maintenance or intervention is required in performing the test. This has obvious benefits in cost and reliability.

I hope the simple code is useful to understand the concept. Happy CAPTCHA-ing!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)