php实现动态验证码
PHP 实现动态验证码的方法
使用 GD 库生成验证码图片
创建画布并生成随机字符串作为验证码内容。通过 GD 库函数绘制干扰线和噪点,输出为图片格式。
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
for ($i = 0; $i < 4; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(200, 255), rand(200, 255), rand(200, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
前端调用验证码
在 HTML 页面中通过 img 标签引用验证码生成脚本,点击可刷新验证码。
<img src="captcha.php" id="captcha" onclick="refreshCaptcha()">
<script>
function refreshCaptcha() {
document.getElementById('captcha').src = 'captcha.php?' + Math.random();
}
</script>
验证用户输入
提交表单时比对用户输入与 session 存储的验证码是否一致。
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']);
?>
增加安全性措施
验证码应设置有效期,通常为 5-10 分钟。生成后立即从 session 删除旧验证码,防止重复使用。
$_SESSION['captcha_time'] = time();
if (time() - $_SESSION['captcha_time'] > 300) {
unset($_SESSION['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(); ?>
这些方法涵盖了从基础实现到高级应用的验证码生成方案,可根据项目需求选择适合的方式。注意验证码应具备足够的复杂度以防止自动化工具破解,同时保持用户可读性。






