php验证码的实现
PHP验证码的实现方法
使用GD库生成基础验证码
创建一个PHP文件(如captcha.php),用于生成验证码图片:
<?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 = substr(str_shuffle($chars), 0, 6);
$_SESSION['captcha'] = $code;
// 添加干扰元素
for ($i = 0; $i < 10; $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 < 6; $i++) {
$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
imagettftext($image, 18, rand(-15, 15), 10 + $i * 20, 30, $color, 'arial.ttf', $code[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
在HTML表单中使用验证码
<form action="submit.php" method="post">
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" placeholder="输入验证码">
<button type="submit">提交</button>
</form>
验证用户输入
创建submit.php文件处理验证:
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
unset($_SESSION['captcha']); // 销毁会话中的验证码
?>
增强安全性措施
使用更复杂的干扰元素:
// 在captcha.php中添加
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocatealpha($image, rand(0, 255), rand(0, 255), rand(0, 255), 70);
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
使用现代验证码库
考虑使用gregwar/captcha等Composer包:
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();
?>
防止自动化攻击
添加验证码尝试次数限制:
// 在submit.php中
if (!isset($_SESSION['attempts'])) {
$_SESSION['attempts'] = 0;
}
$_SESSION['attempts']++;
if ($_SESSION['attempts'] > 3) {
die("尝试次数过多");
}






