How to Implement the CAPTCHA with PHP and GD

So, you have a public submission form on your website (contact page, forum submission):

Contact us (Post new message):

<form method="post" action="">
<table bgcolor="#CCCCCC">
<tr><th>Contact us (Post new message):</th></tr>
<tr><td><textarea cols="30" rows="5"></textarea></td></tr>
<tr><th><input type="submit" value="Submit"></th></tr>    
</table>
</form>

and need to prevent spam auto-submitters. Common way to do this is to implement CAPTCHA - an image with randomly generated string:

image 1

Simple and quick PHP solution:

1. Make a PHP script which will generate the image:

<?php
session_start();
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); 

function _generateRandom($length=6)
{
    $_rand_src = array(
        array(48,57) //digits
        , array(97,122) //lowercase chars
//        , array(65,90) //appercase chars
    );
    srand ((double) microtime() * 1000000);
    $random_string = "";
    for($i=0;$i<$length;$i++){
        $i1=rand(0,sizeof($_rand_src)-1);
        $random_string .= chr(rand($_rand_src[$i1][0],$_rand_src[$i1][1]));
    }
    return $random_string;
}

$im = @imagecreatefromjpeg("captcha.jpg"); 
$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0);
$rand = _generateRandom(3);
$_SESSION['captcha'] = $rand;
ImageString($im, 5, 2, 2, $rand[0]." ".$rand[1]." ".$rand[2]." ", $black);
$rand = _generateRandom(3);
ImageString($im, 5, 2, 2, " ".$rand[0]." ".$rand[1]." ".$rand[2], ImageColorAllocate ($im, 255, 0, 0));
Header ('Content-type: image/jpeg');
imagejpeg($im,NULL,100);
ImageDestroy($im);
?>

2. Add the following line at the top of the page where you need to implement CAPTCHA:

<?php session_start() ?>

3. Add the following line to check is CAPTCHA entered by visitor valid, before the line where you will proceed submitted message:

<?php 
if($_SESSION["captcha"]==$_POST["captcha"])
{
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
}
?>

4. Finaly add the CAPTCHA to the form:

Contact us (Post new message):
CAPTCHA:
(antispam code, 3 black symbols)
image 2

<?php session_start() ?>
<form method="post" action="">
<table bgcolor="#CCCCCC">
<tr><th>Contact us (Post new message):</th></tr>
<tr><td><textarea cols="30" rows="5" name="message"></textarea></td></tr>
<tr><td align="center">CAPTCHA:<br>
    (antispam code, 3 black symbols)<br>
    <table> <tr> <td> <img src="captcha.php" alt="captcha image"> </td> <td> <input type="text" name="captcha" size="3" maxlength="3"> </td> </tr> </table>
</td></tr>
<tr><th><input type="submit" value="Submit"></th></tr>    
</table>
</form>
<?php
if(isset($_POST["captcha"]))
if($_SESSION["captcha"]==$_POST["captcha"])
{
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
    echo 'CAPTHCA is valid; proceed the message';
}
else
{
    echo 'CAPTHCA is not valid; ignore the submission';
}
?>

Related Articles

  • Getting Visitors To Stay Through Web Based Marketing
    9/10 times your web site visitors wont stay for more than 15 seconds. This is how you get them to stay, or should I say, get them to come back! For most of you, your web site is a great brochure. It probably outlines your services very well. Theres nothing wrong with that what-so-ever!
  • Getting A Better Rank For All Your Pages
    In one of my articles, I discussed how to market your web site link twice. It detailed out how to promote not only www.yoursite.com but how you should also promote your site without the www., like this: http://yoursite.com...
  • Google AdSense Tips
    Google AdSense has been a very good source of income for many webmasters on internet. Many webmasters that have the know-how of implementing AdSense codes correctly into their websites have made lots of money, because if you make the correct implementation you will have more clicks...
  • Get the Bug! Viral Marketing Exposed...
    Most marketers know what it is, but very few have the creativity and know how to implement it. Viral marketing is a process developed that can be used or taken up by other people without your having to work much at it. The question is: How does it apply to affiliate marketing?
  • Five Reasons Why You Need SEO Services
    When you start a new web company or create a new website, one of your first questions will be how do I get traffic?...
  • Google Snatch Lets You Discover Google's Undisclosed Pay Per Click Secret
    Google Snatch is your chance to legally snatch money from Googles pockets. There are so many E-books that claim to have the latest answers to making money online. Some work for a while and then fade as Internet time goes by. So is Google Snatch all that it is hyped up to be?
  • Javascripts For Your Website
    Here is a list of short but invaluable Java scripts you can insert into your own site code to implement a number of small but extremely useful features.
  • Top 10 Design / Marketing Tips
    When it comes to designing your site, there are 2 ways you can ultimately go. a) Designing for yourself and no one else, b) Designing to fit web marketing and customer attracting methods...
  • Functionality Vs Stylish Design
    The question faced by all web designers at sometime during a project is: How much functionality should I sacrifice for stylish design? I know that I have played this balancing game many times. However there is a way to have both in healthy servings...
  • Hiring A Custom Website Designer
    Hiring someone to build or promote your website costs considerably more than building it yourself, but it can be a good way to quickly get your site online and start doing business, especially if the site you intend to build is relatively complex or you need to implement an e-commerce solution...

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.