PHP网页验证码是一种用于防止自动化程序(如机器人)进行恶意操作的安全措施。它通常由一组随机生成的字符组成,显示在网页上供用户输入。用户在提交表单时,需要同时提交验证码,服务器端会验证用户输入的验证码是否正确。
<?php
session_start();
// 生成随机验证码
$code = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 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);
imagestring($image, 5, 20, 5, $code, $textColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
<!DOCTYPE html>
<html>
<head>
<title>验证码示例</title>
</head>
<body>
<img src="captcha.php" alt="验证码">
<form action="verify.php" method="post">
<input type="text" name="captcha" placeholder="请输入验证码">
<button type="submit">提交</button>
</form>
</body>
</html>
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userCaptcha = $_POST['captcha'];
if ($userCaptcha == $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
?>
captcha.php
文件中的图像生成代码,确保字符生成和图像生成逻辑正确。session_start()
函数。通过以上步骤和示例代码,你可以在PHP网页中实现验证码的生成和验证。
领取专属 10元无门槛券
手把手带您无忧上云