答案:通过PHP的GD库生成含随机4位字符的验证码图片并存储于Session,用户提交后校验输入与Session值是否一致(忽略大小写),校验后清除Session防止重用,同时建议添加有效期、干扰线、字体美化及IP请求限制等安全措施。

验证码是防止机器人自动提交表单的重要手段。在PHP中,通过GD库可以轻松生成图形验证码,并结合Session实现校验功能。下面介绍一个完整的验证码生成与校验流程。
以下是一个简单的PHP验证码生成函数,它会创建一张包含随机4位数字字母组合的图片:
function generateCaptcha($width = 80, $height = 30) {
// 启动Session用于保存验证码值
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
<pre class='brush:php;toolbar:false;'>// 生成随机验证码文本(4位)
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$captchaText = '';
for ($i = 0; $i < 4; $i++) {
$captchaText .= $chars[rand(0, strlen($chars) - 1)];
}
// 将验证码存入Session
$_SESSION['captcha'] = $captchaText;
// 创建画布
$image = imagecreate($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑色文字
$lineColor = imagecolorallocate($image, 200, 200, 200); // 干扰线颜色
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 写入验证码文本(使用内置字体)
$fontSize = 5;
$textX = ($width - imagefontwidth($fontSize) * 4) / 2;
$textY = ($height - imagefontheight($fontSize)) / 2;
imagestring($image, $fontSize, $textX, $textY, $captchaText, $textColor);
// 输出图像头并显示图片
header('Content-Type: image/png');
imagepng($image);
// 销毁图像资源
imagedestroy($image);}
将上述函数保存为 captcha.php 文件,然后在需要显示验证码的地方使用如下代码:
立即学习“PHP免费学习笔记(深入)”;
// captcha.php require_once 'path/to/generateCaptcha.php'; generateCaptcha();
在HTML中通过img标签引用:
<img src="captcha.php" alt="验证码">
用户提交表单后,需比对输入值与Session中保存的验证码是否一致:
if ($_POST['captcha_input']) {
$userInput = strtoupper(trim($_POST['captcha_input']));
$storedCaptcha = $_SESSION['captcha'] ?? '';
<pre class='brush:php;toolbar:false;'>if ($userInput === $storedCaptcha) {
echo "验证码正确";
} else {
echo "验证码错误";
}}
注意:校验完成后建议清空Session中的验证码,防止重复使用:
unset($_SESSION['captcha']);
基本上就这些。验证码的核心在于“服务端存储 + 图像输出 + 提交校验”,实现简单但有效。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号