PHP验证码(CAPTCHA)是一种用于区分人类和计算机的程序,通常用于网站的安全验证。它通过显示一组扭曲的字符或图像,要求用户输入所显示的内容,以此来防止自动化程序(如机器人)进行恶意操作。
以下是一个简单的PHP文本验证码生成和验证的示例:
<?php
session_start();
// 生成验证码
function generateCaptcha() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 6;
$captcha = '';
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, strlen($characters) - 1)];
}
$_SESSION['captcha'] = $captcha;
return $captcha;
}
// 验证验证码
function verifyCaptcha($input) {
if (isset($_SESSION['captcha']) && $_SESSION['captcha'] === $input) {
return true;
}
return false;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$inputCaptcha = $_POST['captcha'];
if (verifyCaptcha($inputCaptcha)) {
echo "验证码正确!";
} else {
echo "验证码错误!";
}
} else {
$captcha = generateCaptcha();
?>
<!DOCTYPE html>
<html>
<head>
<title>验证码示例</title>
</head>
<body>
<h1>请输入验证码</h1>
<img src="data:image/png;base64,<?php echo base64_encode(gdImage($captcha)); ?>" alt="验证码">
<form method="post">
<input type="text" name="captcha" required>
<button type="submit">提交</button>
</form>
</body>
</html>
<?php
}
?>
<?php
function gdImage($captcha) {
$width = 150;
$height = 50;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 15, 35, $textColor, 'arial.ttf', $captcha);
ob_start();
imagepng($image);
imagedestroy($image);
return ob_get_clean();
}
?>
通过以上示例代码和解释,您可以了解PHP验证码的基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云