PHPackages                             wpjscc/captcha - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. wpjscc/captcha

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

wpjscc/captcha
==============

Framework-agnostic captcha library with pluggable file driver

v1.0.0(yesterday)00MITPHPPHP ^8.1

Since Jun 9Pushed yesterdayCompare

[ Source](https://github.com/wpjscc/captcha)[ Packagist](https://packagist.org/packages/wpjscc/captcha)[ RSS](/packages/wpjscc-captcha/feed)WikiDiscussions master Synced yesterday

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

Captcha
=======

[](#captcha)

与框架无关的 PHP 验证码库，API 设计参考 [mewebstudio/captcha](https://github.com/mewebstudio/captcha)。

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

要求
--

[](#要求)

- PHP &gt;= 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 支持（常驻进程）

[](#多-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 模式（无状态）

[](#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
-------

[](#license)

MIT

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/76907477?v=4)[wpjscc](/maintainers/wpjscc)[@wpjscc](https://github.com/wpjscc)

---

Top Contributors

[![wpjscc](https://avatars.githubusercontent.com/u/76907477?v=4)](https://github.com/wpjscc "wpjscc (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/wpjscc-captcha/health.svg)

```
[![Health](https://phpackages.com/badges/wpjscc-captcha/health.svg)](https://phpackages.com/packages/wpjscc-captcha)
```

###  Alternatives

[ziming/laravel-zxcvbn

Zxcvbn Password validation rule for Laravel

3064.3k](/packages/ziming-laravel-zxcvbn)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
