wpjscc/captcha

Framework-agnostic captcha library with pluggable file driver

Maintainers

Package info

github.com/wpjscc/captcha

pkg:composer/wpjscc/captcha

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-06-09 00:55 UTC

This package is auto-updated.

Last update: 2026-06-09 00:59:36 UTC


README

与框架无关的 PHP 验证码库,API 设计参考 mewebstudio/captcha

支持可插拔的文件驱动,默认提供本地文件驱动;同时支持会话模式与无状态 API 模式。

要求

  • PHP >= 8.1
  • ext-gd
  • ext-json

安装

composer require captcha/captcha

快速开始

use Captcha\Captcha;

$captcha = Captcha::createWithLocalDriver([
    'storageDirectory' => '/tmp/captcha-storage',
]);

// 生成验证码
$response = $captcha->create();

// 输出图片
header('Content-Type: image/jpeg');
echo $response->imageBinary;

// 校验(会话模式)
$valid = $captcha->check($_POST['captcha']);

使用方式

注入文件驱动

实例化时传入 FileDriverInterface,第三方可自行实现(如 OSS、S3 等):

use Captcha\Captcha;
use Captcha\Drivers\LocalFileDriver;
use Captcha\Drivers\LocalStorage;

$fileDriver = new LocalFileDriver();
$storage = new LocalStorage($fileDriver, '/tmp/captcha-storage');

$captcha = new Captcha(
    fileDriver: $fileDriver,
    config: [
        'fontsDirectory' => '/path/to/fonts',
        'bgsDirectory' => '/path/to/backgrounds',
    ],
    storage: $storage,
);

也可使用快捷方法,内置 LocalFileDriver

$captcha = Captcha::createWithLocalDriver();

会话模式

适用于传统 Web 表单,验证码状态保存在 Storage 中:

$response = $captcha->create();

// 返回 HTML img 标签
echo $captcha->img();

// 返回图片 URL(需自行实现对应路由)
$url = $captcha->src(baseUrl: 'https://example.com/captcha');

// 提交后校验
if ($captcha->check($input)) {
    // 验证通过
}

多 Session 支持(常驻进程)

LocalStorage 可按 sessionId 隔离多个会话,适合 Swoole / Workerman 等只实例化一次的场景:

// 进程启动时实例化一次
$captcha = Captcha::createWithLocalDriver([
    'storageDirectory' => '/tmp/captcha-storage',
]);

// 每个请求传入用户唯一标识(如 PHP Session ID、JWT jti 等)
$sessionId = $request->sessionId;

$response = $captcha->create(sessionId: $sessionId);
$valid = $captcha->check($input, sessionId: $sessionId);

不传 sessionId 时默认使用 'default'。同一 sessionId 下仍只保留最新一张验证码(刷新会覆盖旧的)。

API 模式(无状态)

适用于前后端分离场景,生成时返回 key 和 base64 图片,校验时携带 key

// 生成
$api = $captcha->create('math', api: true);
// [
//     'sensitive' => false,
//     'key'       => '...',
//     'img'       => 'data:image/jpeg;base64,...',
// ]

// 校验(对应 Laravel 的 captcha_api 规则)
$valid = $captcha->checkApi(
    value: $_POST['captcha'],
    key: $_POST['key'],
    config: 'math',
);

预设配置

内置多种配置方案,通过第一个参数切换:

$captcha->create('default');  // 默认
$captcha->create('flat');     // 扁平风格
$captcha->create('mini');     // 迷你尺寸
$captcha->create('inverse');  // 反色风格
$captcha->create('math');     // 算术验证码

配置

构造函数第二个参数可覆盖默认配置,完整默认值见 config/captcha.php

$captcha = Captcha::createWithLocalDriver([
    'disable'          => false,          // 设为 true 时 check/checkApi 直接返回 true
    'fontsDirectory'   => '/path/fonts',
    'bgsDirectory'     => '/path/backgrounds',
    'storageDirectory' => '/tmp/captcha',
    'encryptionKey'    => 'your-secret-key',
    'default' => [
        'length'  => 6,
        'width'   => 345,
        'height'  => 65,
        'expire'  => 60,    // 过期时间(秒)
        'math'    => false,
        'encrypt' => false,
    ],
]);
配置项 说明
length 验证码字符长度
width / height 图片尺寸
math 启用算术验证码(如 12 + 3 =
sensitive 区分大小写
expire 过期时间(秒)
encrypt 是否加密存储 key
bgImage 是否使用背景图
bgColor 背景颜色(bgImage=false 时生效)
fontColors 字体颜色列表

自定义文件驱动

实现 Captcha\Contracts\FileDriverInterface 接口:

use Captcha\Contracts\FileDriverInterface;

class OssFileDriver implements FileDriverInterface
{
    public function files(string $directory): array { /* 返回目录下所有文件绝对路径 */ }
    public function exists(string $path): bool { /* ... */ }
    public function read(string $path): string { /* ... */ }
    public function write(string $path, string $contents): bool { /* ... */ }
    public function delete(string $path): bool { /* ... */ }
    public function makeDirectory(string $path, int $mode = 0755): bool { /* ... */ }
}

自定义存储驱动

实现 Captcha\Contracts\StorageInterface 接口,可对接 Redis、Memcached 等:

use Captcha\Contracts\StorageInterface;

class RedisStorage implements StorageInterface
{
    public function putSession(string $sessionId, array $data): void { /* ... */ }
    public function getSession(string $sessionId): ?array { /* ... */ }
    public function removeSession(string $sessionId): void { /* ... */ }
    public function hasSession(string $sessionId): bool { /* ... */ }
    public function putCache(string $key, string $value, int $ttl): void { /* ... */ }
    public function pullCache(string $key): ?string { /* ... */ }
}

项目结构

captcha/
├── assets/
│   ├── fonts/              # 字体文件
│   └── backgrounds/        # 背景图片
├── config/captcha.php      # 默认配置
├── src/
│   ├── Captcha.php         # 核心类
│   ├── CaptchaResponse.php # 响应对象
│   ├── ImageGenerator.php  # GD 图片生成
│   ├── Contracts/
│   │   ├── FileDriverInterface.php
│   │   └── StorageInterface.php
│   └── Drivers/
│       ├── LocalFileDriver.php
│       └── LocalStorage.php
└── tests/

测试

composer install
./vendor/bin/phpunit

License

MIT