PHPackages                             namesfang/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. namesfang/captcha

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

namesfang/captcha
=================

图片验证码

1.1.0(4y ago)0199MITPHPPHP &gt;=7.0

Since Oct 15Pushed 4y ago1 watchersCompare

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

READMEChangelogDependenciesVersions (3)Used By (0)

图形验证码
=====

[](#图形验证码)

### 完整示例

[](#完整示例)

```
use Namesfang\Captcha\Option;
use Namesfang\Captcha\Bundle;

/**
 * 以下为示例所需
 * 实际使用时框架不需要引入
 */
define('ROOT_PATH', dirname(__DIR__));

spl_autoload_register(function ($className) {
    $className = str_replace('\\', '/', $className);
    $className = str_replace('Namesfang/Captcha/', '', $className);
    require_once sprintf('%s/src/%s.php', ROOT_PATH, $className);
});

// +-----------------------------------------------------------
// | 参数配置
// +-----------------------------------------------------------
$option = new Option();

/**
 * 第1种方式
 * 实例化时设置常用参数
 * 3个参数非必填
 */
//$option = new Option(200, 60, 'love');

/**
 * 第2种方式
 * 设置验证码图像宽度
 */
//$option->setWidth(200);

/**
 * 第2种方式
 * 设置验证码图像高度
 */
//$option->setHeight(40);

/**
 * 第2种方式
 * 设置验证码
 * 如不设置验证码，程序会自动
 * 设置后程序会自动计算 length 不需要再次 setLength()
 * 如设置长度少于3则使用 0 补足
 */
//$option->setPhrase('love');

/**
 * 第2种方式
 * 设置验证码长度（用于自动生成）
 * 可用数值 4-6
 * 注意：设置length会自动生成验证码
 */
//$option->setLength(6);

/**
 * 设置验证码文字为单色模式，默认多彩模式
 */
//$option->setPlain();

/**
 * 设置特效 默认开启
 */
//$option->setEffect(false);

/**
 * 设置图片质量
 * 可用数值 0-9
 */
// $option->setQuality(3);

/**
 * 设置自定义字体
 * 如果字体为中文时可能需要设置 $size_adjustment 参数微调
 */
//$option->setFont('path/to/font.ttf');

/**
 * 设置纯色背景
 * 相当于 setBackground(200, 200, 200)
 */
//$option->setBackground(200);

/**
 * 设置纯色背景（16进制）
 * 相当于 setBackgroundHex('3399ff')
 */
//$option->setBackgroundHex('39f');

/**
 * 设置为透明背景
 */
//$option->setBackgroundTransparent();

/**
 * 设置图片
 */
//$option->setBackgroundImage('path/to/image.jpg');

// +-----------------------------------------------------------
// | 验证码缓存并校验
// +-----------------------------------------------------------
/**
 * 将验证码存储到会话
 * 记得先session_start() 一般框架会自动处理
 */
// $_SESSION['captcha'] = $option->getPhrase();
// 校验
//if($_SESSION['captcha'] === $_POST['captcha']) {
//    // 验证成功
//} else {
//    // 验证失败
//}

/**
 * 使用APCu扩展进行缓存
 */
//if(apcu_enabled()) {
//    // 使用APCu扩展进行缓存
//    apcu_store('captcha', $option->getPhrase());
//    // 校验
//}

/**
 * 使用Redis扩展进行缓存
 */
//if(extension_loaded('redis')) {
//    $redis = new \Redis();
//    $redis->connect('127.0.0.1',6379);
//    // 使用Redis扩展进行缓存
//    $redis->set('captcha', $option->getPhrase());
//    // 校验
//    if($redis->get('captcha') === $_POST['captcha']) {
//        // 验证破功
//    } else {
//        // 验证失败
//    }
//    $redis->close();
//}

// +-----------------------------------------------------------
// | 验证码输出到浏览器
// +-----------------------------------------------------------
$bundle = new Bundle($option);

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

$bundle->output();
```

### 输出到浏览器

[](#输出到浏览器)

```
/**
 * 当前验证码地址
 * 您的验证码链接：path/to/examples/output.php
 */
$option = new Option();

/**
 * 这里可以配置相关参数
 */

$bundle = new Bundle($option);

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

$bundle->output();
```

```

```

### 使用（Data URI scheme）

[](#使用data-uri-scheme)

```
$option = new Option();

/**
 * 这里可以配置相关参数
 */

$bundle = new Bundle($option);

/**
 * 后端验证码接口
 * 你的验证码接口地址：path/to/inline.php
 */
echo json_encode([
    'code'=> 0,
    'msg'=> 'ok',
    'data'=> $bundle->inline(), // data:image/png;base64,xxxxxx
]);
```

```
/**
 * 前端js从后端获取验证码数据
 */
jQuery.get('path/to/inline.php', function (pl) {
   if(0 === pl.code) {
       $('#captcha_container').html('');
   }
});
```

### 保存验证码到文件

[](#保存验证码到文件)

```
$option = new Option();

$bundle = new Bundle($option);

/**
 * 将验证码保存到本地
 */
file_put_contents('/path/to/captcha.png', $bundle->stream());
```

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

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

Every ~11 days

Total

2

Last Release

1710d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5258216?v=4)[堪笑](/maintainers/namesfang)[@namesfang](https://github.com/namesfang)

---

Top Contributors

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

---

Tags

captcha

### Embed Badge

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

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

###  Alternatives

[karser/karser-recaptcha3-bundle

Google ReCAPTCHA v3 for Symfony

1872.6M14](/packages/karser-karser-recaptcha3-bundle)[laminas/laminas-captcha

Generate and validate CAPTCHAs using Figlets, images, ReCaptcha, and more

2419.6M51](/packages/laminas-laminas-captcha)[captcha-com/symfony-captcha-bundle

Symfony Captcha Bundle -- BotDetect PHP CAPTCHA generator integration for the Symfony framework.

3992.0k](/packages/captcha-com-symfony-captcha-bundle)[abanoubnassem/filament-grecaptcha-field

Provides a Google reCaptcha V2 field for the Filament Forms

27130.6k2](/packages/abanoubnassem-filament-grecaptcha-field)[aryehraber/statamic-captcha

Protect your Statamic forms using a Captcha service

17211.2k](/packages/aryehraber-statamic-captcha)[mobicms/captcha

A simple PHP CAPTCHA library

2619.4k5](/packages/mobicms-captcha)

PHPackages © 2026

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