php实现获取验证码
使用GD库生成验证码
在PHP中,可以通过GD库来生成验证码图片。以下是一个简单的实现示例:
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 6;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 'path/to/font.ttf'; // 替换为实际字体路径
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 20, 30, $color, $font, $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
添加干扰元素
为了增强验证码的安全性,可以添加干扰线和噪点:
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
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(150, 250), rand(150, 250), rand(150, 250));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
验证码验证
在表单提交时验证用户输入的验证码:
<?php
session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
echo '验证码错误';
} else {
echo '验证码正确';
}
unset($_SESSION['captcha']); // 使用后销毁session
?>
使用第三方库
可以使用现成的验证码库如Gregwar/Captcha:
安装:
composer require gregwar/captcha
使用:
<?php
require_once 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;
session_start();
$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['captcha'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();
?>
验证:
if ($builder->testPhrase($_POST['captcha'])) {
echo '验证码正确';
}
安全建议
验证码应设置有效期,通常在session中存储5-10分钟后失效。避免使用简单的数学运算验证码,容易被破解。对于高安全性需求,可考虑使用行为验证码如滑动验证。







