验证码用于防止自动化程序恶意提交表单,PHP通过生成随机字符并绘制成带干扰元素的图片,结合Session存储验证。

验证码的作用是防止自动化程序恶意提交表单,比如登录、注册等场景。PHP生成验证码的核心原理是:在服务器端生成随机字符,将字符绘制到图片上,并通过 Session 保存原始值,供后续验证使用。
1. 随机字符生成:使用 PHP 的随机函数(如 rand() 或 mt_rand())生成一组数字或字母组合,通常为4-6位。
2. 图像绘制:利用 GD 库创建画布,将字符绘制到图像上,并加入干扰元素(如噪点、干扰线)提高识别难度。
3. Session 存储:将生成的验证码文本存储在 Session 中,用于后续用户提交时比对。
立即学习“PHP免费学习笔记(深入)”;
4. 输出图像:设置正确的内容类型(image/png),输出图像并释放资源。
<?php
session_start();
<p>// 验证码配置
$width = 120;
$height = 40;
$length = 4;</p><p>// 字符集(避免易混淆字符如0,O,l,1等)
$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';</p><p>// 创建图像资源
$image = imagecreatetruecolor($width, $height);</p><p>// 颜色定义
$bgColor = imagecolorallocate($image, 240, 240, 240);
$textColor = imagecolorallocate($image, 0, 0, 0);
$noiseColor = imagecolorallocate($image, 150, 150, 150);</p><p>// 填充背景
imagefill($image, 0, 0, $bgColor);</p><p>// 生成随机验证码
$code = '';
for ($i = 0; $i < $length; $i++) {
$char = $chars[mt_rand(0, strlen($chars) - 1)];
$code .= $char;</p><pre class='brush:php;toolbar:false;'>// 字体大小和位置随机
$fontSize = mt_rand(14, 18);
$x = intval($width / $length * ($i + 0.3));
$y = mt_rand(20, 25);
// 绘制字符
imagestring($image, $fontSize, $x, $y, $char, $textColor);}
// 添加噪点 for ($i = 0; $i zuojiankuohaophpcn 50; $i++) { imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $noiseColor); }
// 添加干扰线 for ($i = 0; $i < 3; $i++) { imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $noiseColor); }
// 存入 Session $_SESSION['captcha'] = strtolower($code);
// 输出图像 header('Content-Type: image/png'); imagepng($image);
// 释放内存 imagedestroy($image); ?>
在 HTML 表单中嵌入验证码图片:
<p>
<label>验证码:<input type="text" name="captcha" /></label>
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer;" />
</p>
点击图片刷新使用 JS 动态加随机参数防止缓存。
用户提交后验证代码:
if (isset($_POST['captcha'])) {
if ($_POST['captcha'] == $_SESSION['captcha']) {
echo "验证成功";
} else {
echo "验证码错误";
}
}
基本上就这些。只要开启 Session、启用 GD 扩展,这段代码就能直接运行。注意安全:验证码使用一次后建议清空 Session,防止重复使用。
以上就是PHP验证码怎么生成_PHP验证码的生成原理与代码实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号