php实现验证码
使用PHP生成验证码
PHP可以通过GD库生成图形验证码,以下是一个完整的实现方法:
创建验证码图片
// 开启session
session_start();
// 创建空白图像
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
// 设置背景色
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 生成随机验证码
$code = '';
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 存储验证码到session
$_SESSION['captcha'] = $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);
}
// 添加噪点
for ($i = 0; $i < 100; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
// 输出验证码文本
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 8, $code, $textColor);
// 输出图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
前端显示验证码
将上述代码保存为captcha.php,在HTML中引用:
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer;" title="点击刷新验证码">
验证用户输入
session_start();
if (strtolower($_POST['captcha']) == strtolower($_SESSION['captcha'])) {
// 验证码正确
} else {
// 验证码错误
}
使用第三方库生成验证码
如果需要更复杂的验证码,可以考虑使用第三方库:
安装Gregwar/Captcha
通过Composer安装:
composer require gregwar/captcha
使用示例
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
安全性增强建议
- 验证码字符长度建议4-6位
- 验证码应区分大小写或统一转换为小写比较
- 限制验证码尝试次数防止暴力破解
- 验证码过期时间设置为5-10分钟
- 使用更复杂的干扰元素提高安全性
- 考虑添加算术验证码等更复杂形式
常见问题解决
- 确保服务器安装了GD库
- 检查session是否正常开启
- 验证码图片不显示时检查MIME类型是否正确
- 验证失败时检查字符大小写是否一致
- 生产环境应避免使用简单数字验证码
以上方法提供了从简单到复杂的PHP验证码实现方案,可根据项目需求选择合适的实现方式。







