验证码(CAPTCHA)是一种用于区分人类和计算机的程序,通常用于网站的安全验证。它通过要求用户识别并输入图像中的文字或数字来防止自动化程序的攻击。
以下是一个简单的PHP示例,展示如何生成和验证图像验证码:
<?php
session_start();
// 生成随机验证码
$code = substr(md5(uniqid(mt_rand(), true)), 0, 6);
$_SESSION['captcha'] = $code;
// 创建图像
$image = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 100, 30, $bgColor);
imagettftext($image, 20, 0, 10, 20, $textColor, 'arial.ttf', $code);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
<?php
session_start();
if (isset($_POST['captcha']) && $_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
?>
通过以上示例和解释,你应该能够理解如何在PHP中生成和验证验证码,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云