验证码(CAPTCHA)是一种用于区分人类和计算机的自动化测试方法。它通常用于网站的安全验证,防止恶意机器人进行自动化操作,如注册、登录、评论等。
以下是一个简单的PHP示例,展示如何生成和验证图像验证码:
<?php
session_start();
// 生成随机字符串
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
// 存储到session
$_SESSION['captcha'] = $randomString;
// 创建图像
$image = imagecreatetruecolor(150, 50);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 150, 50, $bgColor);
imagettftext($image, 20, 0, 20, 35, $textColor, 'arial.ttf', $randomString);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
<?php
session_start();
if (isset($_POST['captcha']) && $_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
?>
通过以上方法,可以有效地生成和验证验证码,提高网站的安全性。
领取专属 10元无门槛券
手把手带您无忧上云