php 实现验证码
使用 PHP 实现验证码
生成验证码图片
通过 PHP 的 GD 库生成验证码图片。创建一个 PHP 文件(如 captcha.php),用于生成包含随机字符的图片:

<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$captcha = substr(str_shuffle($chars), 0, 6);
$_SESSION['captcha'] = $captcha;
$font = 'path/to/font.ttf'; // 替换为实际字体路径
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, rand(18, 22), rand(-30, 30), 10 + $i * 20, 30, $color, $font, $captcha[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
前端显示验证码
在 HTML 页面中嵌入验证码图片,并添加刷新功能:

<img src="captcha.php" id="captcha-image" alt="CAPTCHA">
<a href="#" onclick="document.getElementById('captcha-image').src='captcha.php?'+Math.random();return false">刷新</a>
<input type="text" name="captcha" placeholder="输入验证码">
验证用户输入
在表单提交处理页面(如 submit.php)中验证用户输入的验证码:
<?php
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
die('验证码错误');
}
// 验证通过后的逻辑
echo '验证成功';
?>
增强安全性措施
为提升安全性,可采取以下措施:
- 限制验证码尝试次数(通过 Session 记录错误次数)
- 增加干扰线或噪点(在
captcha.php中添加以下代码):
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(150, 255), rand(150, 255), rand(150, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
for ($i = 0; $i < 500; $i++) {
$color = imagecolorallocate($image, rand(200, 255), rand(200, 255), rand(200, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
注意事项
- 确保服务器已安装 GD 库(可通过
phpinfo()检查) - 字体文件需具有可读权限
- 验证码应设置有效期(如 300 秒后失效)
- 生产环境建议使用更复杂的字符组合或数学公式验证码





