验证码(CAPTCHA)是一种用于区分人类和计算机的自动化测试方法。它通常用于网站表单提交,以防止自动化脚本(如机器人)进行恶意操作,如垃圾邮件发送、账户注册等。
以下是一个简单的PHP验证码生成和验证示例:
<?php
session_start();
function generateCaptcha() {
$code = substr(md5(uniqid(rand(), true)), 0, 6);
$_SESSION['captcha'] = $code;
$image = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 20, 5, $code, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
}
function validateCaptcha($userInput) {
if (strtolower($userInput) == strtolower($_SESSION['captcha'])) {
return true;
}
return false;
}
if (isset($_GET['generate'])) {
generateCaptcha();
} elseif (isset($_POST['captcha'])) {
if (validateCaptcha($_POST['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
?>通过以上内容,您可以了解验证码的基本概念、优势、类型、应用场景以及常见问题的解决方法。希望这些信息对您有所帮助。