PHP 生成数字验证码及调用方法

一颗松果
一颗松果
发布时间:2026-10-14| 3人浏览过
原创

本文提供一段完整的 PHP 代码示例,展示如何使用 GD 库生成纯数字验证码并将值存储在 Session 中,以便在登录流程中进行验证。

实现思路

该方案主要包含以下三个核心步骤:

  1. 生成随机字符:从数字 0-9 中随机抽取 4 位作为验证码内容。
  2. 存储验证值:将生成的验证码转换为小写并存入 $_SESSION,忽略大小写以方便输入。
  3. 图像渲染:使用 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程序设计技巧的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。