php验证码怎么实现
使用GD库生成验证码
PHP的GD库可以用于生成验证码图片。以下是实现步骤:
1. 创建画布并设置背景
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
2. 生成随机验证码字符串
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
$code = substr(str_shuffle($chars), 0, 4);
session_start();
$_SESSION['captcha'] = $code; // 存储验证码到Session
3. 在画布上绘制验证码文本
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 8, $code, $textColor);
4. 添加干扰元素(可选)
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);
}
5. 输出图片并释放内存
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
验证用户输入
在表单提交后,验证用户输入的验证码是否与Session中的一致:
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
使用第三方库简化实现
如果需要更复杂的验证码(如扭曲文字、干扰线等),可以使用 gregwar/captcha 库:
1. 安装库
composer require gregwar/captcha
2. 生成验证码
require_once 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['captcha'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();
3. 验证用户输入
if ($builder->testPhrase($_POST['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
注意事项
- 确保服务器已安装GD库(
php-gd)。 - 验证码应避免使用易混淆的字符(如
0和O)。 - 验证码Session应设置较短的有效期,防止暴力破解。
- 前端应通过Ajax或表单提交验证码,避免明文传输。
以上方法提供了基础的PHP验证码实现方案,可根据需求调整复杂度。







