php实现获取验证码
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 = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 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);
}
// 添加噪点
for ($i = 0; $i < 100; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
// 写入验证码文本
$textColor = imagecolorallocate($image, 0, 0, 0);
for ($i = 0; $i < strlen($code); $i++) {
$x = 20 + ($i * 15);
$y = rand(20, 30);
imagestring($image, 5, $x, $y, $code[$i], $textColor);
}
// 输出图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
在 HTML 中调用验证码
将上述代码保存为 captcha.php,然后在 HTML 页面中这样调用:
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
验证用户输入
当用户提交表单时,验证输入的验证码是否匹配:
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
echo "验证码错误";
} else {
echo "验证码正确";
// 继续处理表单
}
使用 Composer 包实现更复杂验证码
对于更高级的需求,可以考虑使用现成的包:
-
安装 gregwar/captcha 包:
composer require gregwar/captcha -
使用示例:
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder; $builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-type: image/jpeg'); $builder->output();

#### 安全注意事项
- 验证码应区分大小写或统一转换为小写比较
- 验证码应在验证后立即从 session 中清除
- 考虑限制验证码的尝试次数
- 验证码应有一定的复杂度,避免简单数字组合
这种方法可以有效地防止自动化脚本提交表单,提高网站安全性。






