php实现验证码
生成验证码图片
使用 PHP 的 GD 库创建验证码图片。需要确保服务器已安装 GD 库扩展。
// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 设置背景色和文字颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
// 生成随机验证码
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 将验证码写入图片
imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', $code);
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 输出图片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
存储验证码
将生成的验证码存储在会话中,以便后续验证。

session_start();
$_SESSION['captcha'] = $code;
验证用户输入
创建表单接收用户输入并与会话中的验证码比对。
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userInput = $_POST['captcha'] ?? '';
if (strtoupper($userInput) === strtoupper($_SESSION['captcha'])) {
echo '验证码正确';
} else {
echo '验证码错误';
}
unset($_SESSION['captcha']);
}
前端集成
在HTML表单中添加验证码图片和输入框。

<form method="post">
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" required>
<button type="submit">提交</button>
</form>
提高安全性
增加验证码的复杂度以提高安全性。
// 使用更复杂的字符集
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
// 添加扭曲效果
function distortImage($image) {
$width = imagesx($image);
$height = imagesy($image);
$temp = imagecreatetruecolor($width, $height);
imagecopy($temp, $image, 0, 0, 0, 0, $width, $height);
for ($y = 0; $y < $height; $y++) {
$shift = rand(-2, 2);
imagecopy($image, $temp, 0, $y, $shift, $y, $width, 1);
}
imagedestroy($temp);
}
验证码过期设置
为验证码设置有效期,通常为5-10分钟。
$_SESSION['captcha_time'] = time();
// 验证时检查时间
if (time() - $_SESSION['captcha_time'] > 600) {
echo '验证码已过期';
}






