php验证码怎么实现
使用GD库生成验证码
PHP中生成验证码通常借助GD库实现。以下是一个基础实现方法:
<?php
session_start();
$width = 120;
$height = 40;
$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[mt_rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
// 绘制验证码文字
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 20, 30, $textColor, 'arial.ttf', $code);
// 添加干扰元素
for ($i = 0; $i < 50; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand() % $width, rand() % $height, $pixelColor);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证码验证处理
在表单提交处理页面中验证用户输入:
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']);
?>
使用Composer包简化实现
可以使用现成的验证码生成库,如gregwar/captcha:
安装:
composer require gregwar/captcha
使用示例:
<?php
require 'vendor/autoload.php';
session_start();
$builder = new Gregwar\Captcha\CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg');
$builder->output();
?>
提高验证码安全性
增加验证码安全性可采取以下措施:
- 使用更复杂的字符组合
- 增加扭曲和变形效果
- 限制验证码尝试次数
- 设置验证码过期时间
- 使用不同字体和颜色
前端调用验证码
HTML页面中调用验证码图片并刷新:

<img src="captcha.php" id="captcha">
<a href="#" onclick="document.getElementById('captcha').src='captcha.php?'+Math.random();">刷新</a>
<input type="text" name="captcha" required>
这些方法提供了从基础到进阶的PHP验证码实现方案,可根据项目需求选择合适的实现方式。






