生成随机的验证码,防止机器人或恶意攻击
文章目录
<?php
// 生成随机验证码
function generateCaptcha($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$captcha = '';
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, strlen($characters) - 1)];
}
return $captcha;}
// 创建验证码图片
function createCaptchaImage($captcha) {
$image = imagecreatetruecolor(120, 40);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 120, 40, $bgColor);
imagettftext($image, 20, 0, 10, 30, $textColor, 'path/to/font.ttf', $captcha);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);}
// 生成验证码并显示图片
$captcha = generateCaptcha();
createCaptchaImage($captcha);
?>
结合了随机生成、图像处理和动态输出等技术,可以有效地防止机器人攻击和恶意访问

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论