PHP 生成数字验证码及调用方法
本文提供一段完整的 PHP 代码示例,展示如何使用 GD 库生成纯数字验证码并将值存储在 Session 中,以便在登录流程中进行验证。
实现思路
该方案主要包含以下三个核心步骤:
- 生成随机字符:从数字 0-9 中随机抽取 4 位作为验证码内容。
- 存储验证值:将生成的验证码转换为小写并存入
$_SESSION,忽略大小写以方便输入。 - 图像渲染:使用 PHP 的 GD 函数绘制图片背景、文字及干扰像素,最终输出为 JPEG 格式的图片数据。
准备工作
确保服务器环境已启用 PHP 的 GD 扩展,这是图像创建所必须的。
第 1 步:创建验证码处理文件
目的:封装验证码生成与输出的逻辑。
操作:新建文件 ShowKey.php,填入以下代码:
<?php
session_start();
//设置COOKIE或Session
function esetcookie($name,$str,$life=0){
//本函数将字符串 str 全部变小写字符串使验证码输入不区分大小写
$_SESSION[$name]=strtolower($str);
}
//获取随机字符
function domake_password($len)
{
$chars = array(
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
);
$charsLen = count($chars) - 1;
shuffle($chars);
$output = "";
for ($i=0; $i<$len; $i++)
{
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}
//显示验证码
function ShowKey(){
$key=domake_password(4); // 获取4位随机数
esetcookie("checkkey",$key); // 写入 session
//优先尝试使用 imagejpeg
if(function_exists("imagejpeg"))
{
header ("Content-type: image/jpeg");
$img=imagecreate(47,20);
$blue=imagecolorallocate($img,102,102,102);
$white=ImageColorAllocate($img,255,255,255);
$black=ImageColorAllocate($img,71,71,71);
imagefill($img,0,0,$blue);
imagestring($img,5,6,3,$key,$white);
for($i=0;$i<90;$i++){
imagesetpixel($img,rand()%70,rand()%30,$black);
}
imagejpeg($img);
imagedestroy($img);
}
// 以下为其他格式(PNG, GIF等)的降级处理,逻辑同上
elseif (function_exists("imagepng")){
header ("Content-type: image/png");
$img=imagecreate(47,20);
$blue=imagecolorallocate($img,102,102,102);
$white=ImageColorAllocate($img,255,255,255);
$black=ImageColorAllocate($img,71,71,71);
imagefill($img,0,0,$blue);
imagestring($img,5,6,3,$key,$white);
for($i=0;$i<90;$i++){ imagesetpixel($img,rand()%70,rand()%30,$black); }
imagepng($img);
imagedestroy($img);
}
elseif (function_exists("imagegif")){
header("Content-type: image/gif");
$img=imagecreate(47,20);
$blue=imagecolorallocate($img,102,102,102);
$white=ImageColorAllocate($img,255,255,255);
$black=ImageColorAllocate($img,71,71,71);
imagefill($img,0,0,$blue);
imagestring($img,5,6,3,$key,$white);
for($i=0;$i<90;$i++){ imagesetpixel($img,rand()%70,rand()%30,$black); }
imagegif($img);
imagedestroy($img);
}
else{
header("content-type:image/jpeg\r\n");
header("Pragma:no-cache\r\n");
header("Cache-Control:no-cache\r\n");
header("Expires:0\r\n");
$fp = fopen("data/vdcode.jpg","r");
}
}
ShowKey();
?>
第 2 步:在前端页面调用
目的:将生成的验证码显示在表单中。
操作:在 HTML 中使用 img 标签引用上述 PHP 文件,并添加简单的 JavaScript 实现点击刷新:
<img src="ShowKey.php" name="KeyImg" id="KeyImg" onClick="KeyImg.src='ShowKey.php?' + Math.random()" >
其中 Math.random() 参数用于防止浏览器缓存导致图片不更新。
第 3 步:表单提交时的验证
操作:当用户提交表单后,在服务端获取用户输入的验证码,并调用 esetcookie 相同的处理(转小写),然后与 $_SESSION['checkkey'] 进行比对。
以上就是PHP编写登录验证码功能的详细内容,更多关于PHP程序设计技巧的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









