阅读量:4
要使用PHP实现验证码,你可以使用GD库和Imagick扩展。以下是一个简单的示例,展示了如何创建一个带有噪点和干扰线的验证码图片:
-
首先,确保你的服务器已经安装了GD库和Imagick扩展。
-
创建一个名为
captcha.php的文件,并在其中添加以下代码:
session_start();
// 生成随机字符串
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// 创建验证码图片
function createCaptchaImage($text) {
$width = 150;
$height = 60;
$image = imagecreatetruecolor($width, $height);
// 设置背景颜色
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $backgroundColor);
// 设置字体颜色
$textColor = imagecolorallocate($image, 0, 0, 0);
// 设置字体大小
$fontSize = 24;
// 计算文本的边界框
$textWidth = imagefontwidth($fontSize, $text);
$textHeight = imagefontheight($fontSize, $text);
// 定位文本位置
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 + $fontSize;
// 在图片上绘制文本
imagettftext($image, $fontSize, 0, $x, $y, $textColor, 'arial.ttf', $text);
// 添加噪点
for ($i = 0; $i < 100; $i++) {
$pointX = rand(0, $width - 1);
$pointY = rand(0, $height - 1);
imagesetpixel($image, $pointX, $pointY, imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)));
}
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineStartX = rand(0, $width - 1);
$lineEndX = rand(0, $width - 1);
$lineY = rand(0, $height - 1);
imageline($image, $lineStartX, $lineY, $lineEndX, $lineY, imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)));
}
return $image;
}
// 输出验证码图片
function outputCaptchaImage() {
$text = generateRandomString();
$image = createCaptchaImage($text);
header('Content-type: image/png');
imagepng($image);
// 将验证码文本保存到会话中
$_SESSION['captcha'] = $text;
// 销毁图片资源
imagedestroy($image);
}
outputCaptchaImage();
?>
- 在你的HTML文件中,添加一个
标签来显示验证码图片:
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码示例title>
head>
<body>
<h1>请输入验证码h1>
<img src="captcha.php" alt="验证码">
<form action="submit_captcha.php" method="post">
<input type="text" name="captcha" required>
<input type="submit" value="提交">
form>
body>
html>
- 创建一个名为
submit_captcha.php的文件,用于处理表单提交:
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userCaptcha = $_POST['captcha'];
$storedCaptcha = $_SESSION['captcha'];
if ($userCaptcha == $storedCaptcha) {
echo "验证成功!";
} else {
echo "验证失败!请重试。";
}
}
?>
现在,当用户访问你的网站并输入验证码时,submit_captcha.php文件将检查用户输入的验证码是否与会话中存储的验证码匹配。如果匹配,用户将被视为合法用户。
以上就是关于“怎么用php实现验证码”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm