简单的验证码图片生成器

下面的PHP程序可以生成如  这样的简单验证码。把它存成一个PHP文件,例如captcha.php,使用<img src=’captcha.php’ />显示它,然后,你在服务器端把用户的输入和$_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);
?>

使用的字符集里没有I、O、1、0、Z、2,因为担心它们互相混淆。思考:S和5是不是也挺像的?纠结。

为了让验证码有“看不清,换一个”的功能,现实中的<img>写得要稍微复杂些,下面代码里的’captcha.php?’+now.getTime()是为了欺骗浏览器,让它以为是一张新的图片进来了,强迫它刷新captcha.php产生的图片,而不是从缓存里获得:

<img src="captcha.php" title="click for a new one"
onclick="now=new Date();src='captcha.php?'+now.getTime();" />
评论关闭