Click here to Skip to main content
Click here to Skip to main content

Securing Web Forms with Simple PHP-CAPTCHA

, 15 Feb 2012
Rate this:
Please Sign up or sign in to vote.
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.

<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.

<?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.

<?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.

<?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.

<?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)

About the Author

sujithfem
Web Developer
India India
Sujith,I Began tinkering with web development as professional in 2004 ,currently working in the IT department ,Insoft,I has experience developing web solution with java script ,PHP,TAL,MYSQL,Oracle and Apache and animation solution with Flash ,Swish and sound Forge.
If you want to know about me more just click my family portal, it’s www.triqtra.co.nr
 

Comments and Discussions

 
Generalthanks, good and simple description PinmemberDanielf197016-Jul-09 21:35 
GeneralVisual Flash CAPTCHA PinmemberSearcherx9-Feb-07 9:18 
Generalsure (from a .net point of view) Pinmemberpointnetsolutions21-Jul-06 7:53 
GeneralOkay but.. PinmemberLaubi20-Jul-06 23:58 
GeneralRe: Okay but.. Pinmembersujithfem24-Jul-06 20:57 
GeneralI have also written some php Captcha [modified] PinmemberPriyank Bolia20-Jul-06 22:01 
GeneralRe: I have also written some php Captcha Pinmembersujithfem24-Jul-06 20:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 15 Feb 2012
Article Copyright 2006 by sujithfem
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid