验证码(CAPTCHA)是一种用于区分人类和计算机的自动化测试程序。它通常用于网站表单提交,以防止恶意机器人进行自动注册、登录或其他恶意操作。
以下是一个简单的PHP图像验证码的实现示例:
<?php
session_start();
// 生成随机字符串
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
// 存储验证码到session
$_SESSION['captcha'] = $randomString;
// 创建图像
$image = imagecreatetruecolor(150, 50);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 150, 50, $backgroundColor);
imagettftext($image, 20, 0, 15, 35, $textColor, 'arial.ttf', $randomString);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Captcha Example</title>
</head>
<body>
<form action="verify.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<label for="captcha">Captcha:</label>
<input type="text" id="captcha" name="captcha">
<img src="captcha.php" alt="Captcha"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['captcha'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$userCaptcha = $_POST['captcha'];
if (strtoupper($userCaptcha) == strtoupper($_SESSION['captcha'])) {
// 验证码正确,进行后续操作
echo "Captcha is correct!";
} else {
// 验证码错误
echo "Captcha is incorrect!";
}
} else {
echo "Invalid request!";
}
?>
通过以上步骤,你可以实现一个简单的PHP图像验证码系统。这个系统可以有效地防止自动化攻击,提高网站的安全性。
领取专属 10元无门槛券
手把手带您无忧上云