PHP数字验证码是一种用于验证用户身份或防止自动化程序(如机器人)进行恶意操作的安全措施。它通常由一组随机生成的数字组成,并显示在网页上供用户输入。服务器端会验证用户输入的验证码是否正确。
以下是一个简单的PHP数字验证码实例:
<?php
session_start();
// 生成验证码
if (empty($_SESSION['captcha'])) {
$_SESSION['captcha'] = rand(1000, 9999);
}
// 验证用户输入的验证码
if (isset($_POST['captcha'])) {
if ($_POST['captcha'] == $_SESSION['captcha']) {
echo "验证码正确!";
} else {
echo "验证码错误!";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP 数字验证码</title>
</head>
<body>
<h1>请输入验证码</h1>
<form method="post">
<label for="captcha">验证码:</label>
<input type="text" id="captcha" name="captcha">
<img src="captcha.php" alt="验证码">
<button type="submit">提交</button>
</form>
</body>
</html>
<?php
session_start();
// 生成验证码
$captcha = rand(1000, 9999);
$_SESSION['captcha'] = $captcha;
// 创建图像
$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, $captcha, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
通过以上代码,你可以生成一个简单的数字验证码,并在网页上显示供用户输入。服务器端会验证用户输入的验证码是否正确。
领取专属 10元无门槛券
手把手带您无忧上云