扫盲 2026.11.01 21:45 17 次浏览 0 条评论

PHP生成简单图片验证码

验证码就是一张带随机字符的图片。PHP 用 GD 库画出来,答案顺手存进 session,提交时拿来比对。开工前先确认 php.ini 里 extension=gd 已经打开,没打开的话 imagecreatetruecolor 会直接报错。

code.php 这样写:

<?php
session_start();
header('Content-Type: image/png');

$w = 100; $h = 36;
$img = imagecreatetruecolor($w, $h);
imagefill($img, 0, 0, imagecolorallocate($img, 245, 245, 245));

$chars = 'ABCDEFGHJKLMNPQRSTUVWXY3456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
$_SESSION['code'] = $code;   // 答案存 session

for ($i = 0; $i < 3; $i++) {   // 几根干扰线
    $c = imagecolorallocate($img, mt_rand(120,200), mt_rand(120,200), mt_rand(120,200));
    imageline($img, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w), mt_rand(0,$h), $c);
}

for ($i = 0; $i < 4; $i++) {   // 挨个写字符
    $c = imagecolorallocate($img, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100));
    imagestring($img, 5, 12 + $i * 20, mt_rand(6,14), $code[$i], $c);
}

imagepng($img);
imagedestroy($img);

页面上当图片引,点一下就换一张:

<img src="code.php" onclick="this.src='code.php?t='+Math.random()">

校验时把输入用 strtoupper(trim()) 处理一下,再跟 $_SESSION['code'] 全等比较就行;比完记得 unset 掉,别重复使用。

说点什么 0

行思随记

欢迎来到:行思随记