验证码(CAPTCHA)是一种用于区分人类和计算机的程序,通常用于网站的安全验证。扭曲验证码是一种常见的验证码类型,通过扭曲、变形、噪点等手段增加图像的复杂性,使得计算机难以识别,而人类用户仍然能够辨认。
以下是一个简单的扭曲验证码生成示例:
<?php
session_start();
// 生成随机字符串
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// 生成扭曲验证码
function generateCaptcha($text) {
$width = 150;
$height = 50;
$image = imagecreatetruecolor($width, $height);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $backgroundColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
$font = 'arial.ttf'; // 确保字体文件存在
// 扭曲图像
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$newX = $x + 10 * sin($y / 10);
$newY = $y + 10 * cos($x / 10);
imagesetpixel($image, $newX, $newY, imagecolorallocate($image, rand(200, 255), rand(200, 255), rand(200, 255)));
}
}
// 添加文字
imagettftext($image, 20, 10, 30, 30, $textColor, $font, $text);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
}
// 生成并保存验证码
$captchaText = generateRandomString();
$_SESSION['captcha'] = $captchaText;
generateCaptcha($captchaText);
?>
通过以上方法,可以有效生成和应用扭曲验证码,提升网站的安全性。
领取专属 10元无门槛券
手把手带您无忧上云