Simple PHP Anti-Spam Captcha Script

Anti-Spam PHP Captcha ExampleOne of the best, if not the best, ways to prevent automated web robot tools and spammers from taking advantage of your forms and scripts is by using a captcha image. Here is a simple example that I hacked up earlier today to use on my Advanced Request and Response HTTP Header Viewer among other tools.

View a working example on my Advanced Request and Response HTTP Header Viewer tool.

PHP Anti-Spam Captcha Example

Save this on your site as capya.php and include in your php script with require_once 'capya.php', then run with askapache_captcha(); which outputs XHTML of the captcha image.

'; } else echo ''; // destroy image imagedestroy($image); // delete all captcha images at 12 and 3 oclock if more than 100 are found $dt=date('g'); if(($dt==12)||($dt=='12'))capya_cleanup(); else if(($dt==3)||($dt=='3'))capya_cleanup(); } function capya_cleanup(){ $files=glob(CAPYADIR."apache*.jpg"); if(sizeof($files)>100){ foreach ($files as $filename) { unlink($filename); //echo "$filename size " . filesize($filename) . "n"; } } } function capya_string($len){ $str=''; for($i=1; $i<=$len; $i++) { $ord=rand(48, 90); if((($ord >= 48) && ($ord <= 57)) || (($ord >= 65) && ($ord<= 90))) $str.=chr($ord); else $str.=capya_string(1); } return $str; } ?>

Verify Captcha

To verify a user-submitted (via POST or GET) value for the captcha image, do this.

Get the Anti-Spam Captcha Code

  1. askapache-captcha.php
  2. Download the TrueType Font files and captcha background image