The code below is to generate a simple CAPTCHA image, like . Save it (as "captcha.php" for instance), and use <img src="captcha.php" /> to display it. On the server side, simply compare the client input with $_SESSION['captcha'].
<?php session_start(); $charset = 'ABCDEFGHJKLMNPQRSTUVWXY3456789'; $maxpos = strlen($charset) - 1; $captcha = ''; $im = imagecreate(60, 24); $white = imagecolorallocate($im, 0xff, 0xff, 0xff); for ($i = 0; $i < 4; $i++) { $imchar = imagecreate(15, 24); $white = imagecolorallocate($imchar,mt_rand(0xe0, 0xff), mt_rand(0xe0, 0xff), mt_rand(0xe0, 0xff)); $color = imagecolorallocate($imchar, mt_rand(0x00, 0x70), mt_rand(0x00, 0x70), mt_rand(0x00, 0x70)); $captcha .= substr($charset, mt_rand(0, $maxpos), 1); imagestring($imchar, 5, 0, 0, $captcha[$i], $color); $imchar = imagerotate($imchar, mt_rand(-10, 10), $white); imagecopymerge($im, $imchar, mt_rand(1, 5) + $i * 15, mt_rand(0, 8), 0, 0, 15, 24, 100); } for ($i = 0; $i < 15; $i++) { $x1 = mt_rand(0, 59); $y1 = mt_rand(0, 23); $x2 = $x1 + mt_rand(-2, 2); $y2 = $y1 + mt_rand(-1, 1); imageline($im, $x1, $y1, $x2, $y2, mt_rand(0x000000, 0xffffff)); } $_SESSION['captcha'] = $captcha; header('Content-type: image/gif'); imagegif($im); ?>
The characters I, 1, O, and 0 are taken out of the character set, for they may confuse the client. Should I take S and 5 out as well?
To make the CAPTCHA image refresh everytime you click it, the <img> tag is a little complex, as below. Here, the now.getTime() is to cheat the web-browser to think that it is a new image, so the image is always reloaded, but not to read the image from the browser's cache.
<img src="captcha.php" title="click for a new one" onclick="now=new Date();src='captcha.php?'+now.getTime();" />
Check it out: