php 实现验证码
使用 PHP 生成验证码
验证码(CAPTCHA)是一种用于区分人类用户和机器自动程序的工具。以下是使用 PHP 生成验证码的详细方法。

创建验证码图像
使用 PHP 的 GD 库生成验证码图像。确保服务器已安装 GD 库。

<?php
session_start();
// 设置验证码参数
$width = 120;
$height = 40;
$length = 6;
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
// 创建图像
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 生成随机验证码
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 存储验证码到 Session
$_SESSION['captcha'] = $code;
// 添加干扰元素
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
// 绘制验证码文本
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, rand(18, 22), rand(-30, 30), 20 + $i * 20, 30, $color, 'arial.ttf', $code[$i]);
}
// 输出图像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
在 HTML 中调用验证码
将验证码图像嵌入到 HTML 表单中,用户提交表单时验证输入。
<form action="submit.php" method="post">
<label for="captcha">验证码:</label>
<input type="text" name="captcha" id="captcha" required>
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
<button type="submit">提交</button>
</form>
验证用户输入
在表单提交处理页面(如 submit.php)中验证用户输入的验证码是否匹配。
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userCaptcha = isset($_POST['captcha']) ? trim($_POST['captcha']) : '';
$sessionCaptcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
if (empty($userCaptcha) || $userCaptcha !== $sessionCaptcha) {
die('验证码错误!');
}
// 验证通过,继续处理表单
echo '验证码正确!';
}
?>
增强验证码安全性
- 限制验证码有效期:在 Session 中存储生成时间,验证时检查是否过期。
- 增加复杂度:使用更多干扰线、噪点或扭曲文本。
- 防止暴力破解:限制验证码尝试次数。
// 存储验证码生成时间
$_SESSION['captcha_time'] = time();
// 验证时检查时间(例如 5 分钟内有效)
if (time() - $_SESSION['captcha_time'] > 300) {
die('验证码已过期!');
}
通过以上方法,可以快速实现一个基本的 PHP 验证码功能,并根据需求进一步优化安全性。






