php实现验证码
使用 PHP 生成验证码
验证码是一种用于区分人类用户和机器人的安全机制。以下是使用 PHP 生成验证码的几种方法。
使用 GD 库生成图片验证码
GD 库是 PHP 中常用的图像处理库,可以用于生成图片验证码。
<?php
session_start();
// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 设置背景色和文字颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefill($image, 0, 0, $bgColor);
// 生成随机验证码
$code = substr(md5(uniqid(rand(), true)), 0, 6);
$_SESSION['captcha'] = $code;
// 在画布上绘制验证码
imagestring($image, 5, 30, 12, $code, $textColor);
// 输出图像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
添加干扰元素
为了提高安全性,可以添加干扰线或干扰点。
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $bgColor);
$code = substr(md5(uniqid(rand(), true)), 0, 6);
$_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);
}
imagestring($image, 5, 30, 12, $code, $textColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证用户输入
生成验证码后,需要验证用户输入是否正确。
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userCaptcha = $_POST['captcha'] ?? '';
$validCaptcha = $_SESSION['captcha'] ?? '';
if ($userCaptcha === $validCaptcha) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
?>
使用 Composer 包
可以使用第三方库如 gregwar/captcha 简化验证码生成。
安装:
composer require gregwar/captcha
使用:
<?php
require 'vendor/autoload.php';
session_start();
$builder = new Gregwar\Captcha\CaptchaBuilder;
$builder->build();
$_SESSION['captcha'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();
?>
前端集成
在 HTML 表单中显示验证码并提交验证。

<form method="post" action="validate.php">
<img src="captcha.php" alt="CAPTCHA" onclick="this.src='captcha.php?'+Math.random();">
<input type="text" name="captcha" required>
<button type="submit">提交</button>
</form>
注意事项
- 验证码应存储在会话中,避免直接暴露在客户端。
- 定期更换验证码,防止重复使用。
- 结合其他安全措施如 IP 限制,提高安全性。
通过以上方法,可以轻松实现 PHP 验证码功能,有效防止自动化攻击。






