Add CAPTCHA anti-spam to your forms with PHP

by admin on July 24, 2009 · 0 comments

Here is a simple function to add to your PHP pages, which will prevent spammers & bots from entering automated comments. It will generate a random number and display that number in an image on the form. You can ask the user to enter the number as they see in the image, and that will prove that they're a real human!

<?php
 
function anti_bot($length=4)
{
     $number = "";
     for ($i = 1; $i <= $length; $i++)
     {
          $number .= rand(0,9) . "";
     }
 
     $width = 12 * $length;
     $height = 30;
 
     $img = ImageCreate($width, $height);
     $background = imagecolorallocate($img,255,255,255);
     $color_black = imagecolorallocate($img,0,0,0);
     $color_grey = imagecolorallocate($img,169,169,169);
     imagerectangle($img,0, 0,$width-1,$height-1,$color_grey);
     imagestring($img, 5, $length, 7, $number, $color_black);
     imagepng($img);
     imagedestroy($img);
}
 
anti_bot();
?>

Previous post:

Next post: