当前位置:首页 > PHP

php 实现验证码

2026-02-13 13:03:53PHP

生成验证码图片

使用 PHP 的 GD 库创建验证码图片,生成随机字符串并绘制到图片上:

session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;

$font = 'path/to/font.ttf'; // 替换为实际字体文件路径
for ($i = 0; $i < 4; $i++) {
    $textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
    imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $textColor, $font, $code[$i]);
}

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

添加干扰元素

增加干扰线和噪点提高安全性:

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
    $lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}

// 添加噪点
for ($i = 0; $i < 200; $i++) {
    $pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
    imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}

前端调用验证码

在 HTML 中显示验证码图片并设置点击刷新:

php 实现验证码

<img src="captcha.php" id="captcha" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" placeholder="输入验证码">

验证用户输入

在表单提交时验证用户输入的验证码:

session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userInput = strtolower(trim($_POST['captcha']));
    $captcha = strtolower($_SESSION['captcha']);

    if ($userInput === $captcha) {
        echo '验证码正确';
    } else {
        echo '验证码错误';
    }
}

提高安全性措施

增加验证码有效期限制和大小写不敏感验证:

php 实现验证码

// 在生成验证码时记录时间
$_SESSION['captcha_time'] = time();

// 验证时检查有效期(5分钟)
if (time() - $_SESSION['captcha_time'] > 300) {
    echo '验证码已过期';
}

使用 Composer 包

对于更复杂的需求,可以考虑使用专业验证码库:

composer require gregwar/captcha

使用示例:

require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;

$builder = new CaptchaBuilder;
$builder->build();
$_SESSION['phrase'] = $builder->getPhrase();
header('Content-Type: image/jpeg');
$builder->output();

标签: 验证码php
分享给朋友:

相关文章

php实现文件下载

php实现文件下载

PHP实现文件下载的方法 通过PHP实现文件下载功能,可以采用多种方式,以下是几种常见的实现方法: 使用header()函数强制下载 设置HTTP头信息,强制浏览器下载文件而非直接打开: $fi…

php实现聊天

php实现聊天

实现 PHP 聊天功能的方法 使用 WebSocket 和 PHP 实现实时聊天 WebSocket 是一种全双工通信协议,适合实现实时聊天功能。PHP 可以通过 Ratchet 库实现 WebSo…

php 实现秒杀

php 实现秒杀

PHP 实现秒杀的关键技术 秒杀系统需要解决高并发、超卖、性能瓶颈等问题。以下是实现秒杀的核心方案: 使用 Redis 预减库存 将商品库存提前加载到 Redis 中,通过原子操作保证库存准确性:…

php 实现类

php 实现类

PHP 类的基本实现 在 PHP 中,类通过 class 关键字定义,后跟类名和一对花括号。类名通常遵循大驼峰命名法(如 ClassName)。以下是基本语法: class ClassName {…

php实现注册登录

php实现注册登录

PHP 注册功能实现 创建数据库表(以 MySQL 为例) CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, usern…

php 实现面包屑导航

php 实现面包屑导航

实现面包屑导航的方法 面包屑导航(Breadcrumb Navigation)是一种常见的网站导航方式,用于显示用户当前页面的路径。以下是几种在 PHP 中实现面包屑导航的方法。 基于 URL 路径…