php验证码实现
PHP验证码实现方法
验证码(CAPTCHA)用于防止自动化脚本提交表单,以下介绍几种PHP实现验证码的方法。
使用GD库生成图片验证码
GD库是PHP内置的图像处理库,适合生成简单验证码。
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
$length = 4;
for ($i = 0; $i < $length; $i++) {
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
imagettftext($image, 20, mt_rand(-30, 30), 10 + $i * 30, 30, $color, 'arial.ttf', $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
增加干扰元素
为提高安全性,可添加干扰线和噪点:

for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
}
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $color);
}
验证用户输入
创建验证页面验证用户输入:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['captcha']) && isset($_SESSION['captcha'])) {
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
unset($_SESSION['captcha']);
}
?>
使用第三方库
对于更复杂需求,可使用以下第三方库:

- Securimage:功能丰富的PHP验证码库
- Gregwar/Captcha:Composer包,支持多种验证码类型
安装Gregwar/Captcha:
composer require gregwar/captcha
使用示例:
<?php
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
?>
前端调用验证码
HTML页面调用验证码图片并提交表单:
<form method="post" action="verify.php">
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" required>
<button type="submit">提交</button>
</form>
安全注意事项
- 验证码应设置有效期(如5分钟)
- 验证后立即销毁session中的验证码
- 避免使用简单字体和纯色背景
- 考虑添加点击刷新功能防止暴力破解
- 对验证失败次数进行限制
以上方法可根据实际需求组合使用,平衡安全性和用户体验。对于高安全场景,建议使用reCAPTCHA等专业服务。






