php实现变色验证码
生成随机验证码
使用PHP的rand()或mt_rand()函数生成随机字符串作为验证码。可以组合数字和字母增加复杂度。
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
创建画布并设置背景
使用imagecreatetruecolor()函数创建画布,设置背景色为白色或其他浅色。
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
添加干扰元素
在画布上添加干扰线或干扰点,防止机器识别。使用随机颜色和位置绘制线条或点。

for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
}
for ($i = 0; $i < 50; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $color);
}
绘制变色验证码
将验证码字符绘制到画布上,每个字符使用不同的颜色和位置。
for ($i = 0; $i < strlen($code); $i++) {
$charColor = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
$x = ($width / strlen($code)) * $i + mt_rand(5, 10);
$y = mt_rand(5, $height - 15);
imagestring($image, 5, $x, $y, $code[$i], $charColor);
}
输出图像并保存验证码
将图像输出为PNG或JPEG格式,同时将验证码存入Session以便后续验证。

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
session_start();
$_SESSION['captcha'] = $code;
完整代码示例
以下是一个完整的PHP变色验证码生成代码:
<?php
session_start();
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
}
for ($i = 0; $i < 50; $i++) {
$color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $color);
}
for ($i = 0; $i < strlen($code); $i++) {
$charColor = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
$x = ($width / strlen($code)) * $i + mt_rand(5, 10);
$y = mt_rand(5, $height - 15);
imagestring($image, 5, $x, $y, $code[$i], $charColor);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
$_SESSION['captcha'] = $code;
?>
验证码验证
在表单提交时,通过比较Session中的验证码和用户输入的值来验证。
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo '验证码正确';
} else {
echo '验证码错误';
}
通过以上步骤,可以实现一个简单的变色验证码功能,有效防止自动化工具的攻击。






