PHPackages                             yiirocks/recaptcha - 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. yiirocks/recaptcha

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

yiirocks/recaptcha
==================

Google reCAPTCHA v2 and v3 field + server-side validator for Yii3.

v1.0.3(3w ago)02.2k1MITPHPPHP &gt;=8.3CI passing

Since Jun 13Pushed 2w agoCompare

[ Source](https://github.com/YiiRocks/recaptcha)[ Packagist](https://packagist.org/packages/yiirocks/recaptcha)[ Docs](https://www.yii.rocks/recaptcha/)[ RSS](/packages/yiirocks-recaptcha/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (4)Dependencies (16)Versions (6)Used By (1)

Yii3 reCAPTCHA
==============

[](#yii3-recaptcha)

[![Packagist Version](https://camo.githubusercontent.com/917864175cfc66322e114761d9f5d0c441981bb9600b43b55ebcd28a068a76f8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f796969726f636b732f7265636170746368612e737667)](https://packagist.org/packages/yiirocks/recaptcha)[![PHP from Packagist](https://camo.githubusercontent.com/b82c7b7fa4e7e38c28e63c673ca11d4b3a8964fed79e221d766cf0a82520243a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f796969726f636b732f7265636170746368612e737667)](https://php.net/)[![Packagist Downloads](https://camo.githubusercontent.com/7ee48d4fdb965c9f49294b2940f39b0ff57b77ce48418d2c3db850514cfe211e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f796969726f636b732f7265636170746368612e737667)](https://packagist.org/packages/yiirocks/recaptcha)[![GitHub License](https://camo.githubusercontent.com/1dabd01e1af3641b96518d68d5a080a1572dad226f4af2948b7c19425148e970/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f796969726f636b732f7265636170746368612e737667)](https://github.com/yiirocks/recaptcha/blob/main/LICENSE.md)[![GitHub Workflow Status](https://camo.githubusercontent.com/823137471869b5cee917be18ad2548f291c13298ab29f8b8d71bcd39073e329a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f596969526f636b732f7265636170746368612f6275696c642e796d6c3f6272616e63683d6d61696e)](https://github.com/YiiRocks/recaptcha/actions)

Stats for Nerds

[![Coverage](https://camo.githubusercontent.com/fc2d87c611858debb0fdfe52c576dad7ee9e019e834ab8e290b9540cf990e189/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d253246796969726f636b73253246726563617074636861253246626164676573253246636f7665726167652e6a736f6e)](https://github.com/yiirocks/recaptcha/tree/badges)[![MSI](https://camo.githubusercontent.com/cdccd293756db484d065de5ece48e39c3ac253d4cdfe5731a38ac23347e1e346/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d253246796969726f636b732532467265636170746368612532466261646765732532466d73692e6a736f6e)](https://github.com/yiirocks/recaptcha/tree/badges)[![Tests](https://camo.githubusercontent.com/7b9b18881c1de9b13968da766812d712ba2fd0093294afbae84e1e7e71d55d69/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d253246796969726f636b7325324672656361707463686125324662616467657325324674657374732e6a736f6e)](https://github.com/yiirocks/recaptcha/tree/badges)[![Assertions](https://camo.githubusercontent.com/adebae96e4d9985b127def3c948e725b2139638242fe3f55a0fdc47a40b4152a/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470732533412532462532467261772e67697468756275736572636f6e74656e742e636f6d253246796969726f636b73253246726563617074636861253246626164676573253246617373657274696f6e732e6a736f6e)](https://github.com/yiirocks/recaptcha/tree/badges)

Google reCAPTCHA v2 and v3 field + server-side validator for Yii3.

Requirements
------------

[](#requirements)

- PHP 8.3+
- PSR-18 HTTP client
- PSR-17 request + stream factories

Installation
------------

[](#installation)

```
composer require yiirocks/recaptcha
```

A PSR-18 client and PSR-17 factories are required. If your application already has them configured (e.g. via Guzzle, Symfony HTTP Client, or any other implementation), no further setup is needed.

If not, install any compatible library, for example:

```
composer require guzzlehttp/guzzle nyholm/psr7
```

Configuration
-------------

[](#configuration)

Set your site keys and secrets either via environment variables or directly in your application's `config/params.php`:

### Environment variables (recommended)

[](#environment-variables-recommended)

```
// config/params.php
return [
    'yiirocks/recaptcha' => [
        'siteKeyV2' => $_ENV['RECAPTCHA_SITE_KEY_V2'] ?? '',
        'secretV2'  => $_ENV['RECAPTCHA_SECRET_V2'] ?? '',
        'siteKeyV3' => $_ENV['RECAPTCHA_SITE_KEY_V3'] ?? '',
        'secretV3'  => $_ENV['RECAPTCHA_SECRET_V3'] ?? '',
    ],
];
```

If the env vars are not set the values fall back to empty strings — override them in your `config/params.php` as needed (the config-plugin merges them).

### All parameters

[](#all-parameters)

ParameterDefaultDescription`siteKeyV2``''` (or `$_ENV`)reCAPTCHA v2 site key`secretV2``''` (or `$_ENV`)reCAPTCHA v2 secret`siteKeyV3``''` (or `$_ENV`)reCAPTCHA v3 site key`secretV3``''` (or `$_ENV`)reCAPTCHA v3 secret`verifyUrl``https://www.google.com/recaptcha/api/siteverify`Google verification endpoint`sendRemoteIp``false`Send the user's IP to Google for abuse analysis`translation.category``recaptcha`Translation category used by message sources> **Tip:** Once your site keys are set, fields will pull them from the registry automatically — no need to call `withSiteKey()` in your view code.

### DI Configuration

[](#di-configuration)

The config-plugin (`config-plugin` in `composer.json`) wires everything automatically:

- `RecaptchaClient` receives `RecaptchaConfig` plus PSR services from the container
- `RecaptchaV2RuleHandler` and `RecaptchaV3RuleHandler` are wired with optional client, request provider, and translator
- The translation category source is registered with the `translation.categorySource` tag
- The bootstrap callback populates `RecaptchaRegistry` with the client, request provider, and translator. This means fields and handlers work out of the box — no explicit `withSiteKey()` needed.

Usage
-----

[](#usage)

All fields are rendered with a form model via the `::field()` static method — the standard Yii3 form field pattern. Validation errors are shown automatically.

### reCAPTCHA v2

[](#recaptcha-v2)

```
use Yiisoft\FormModel\FormModel;
use YiiRocks\Recaptcha\RecaptchaV2Field;
use YiiRocks\Recaptcha\RecaptchaV2Theme;
use YiiRocks\Recaptcha\RecaptchaV2Size;
use YiiRocks\Recaptcha\RecaptchaV2Type;

echo RecaptchaV2Field::field($form, 'captcha')
    ->withTheme(RecaptchaV2Theme::Dark)
    ->withSize(RecaptchaV2Size::Compact)
    ->withType(RecaptchaV2Type::Audio)
    ->withId('my-captcha')
    ->withCallback('onSuccess')
    ->render();
```

Available options:

MethodDefaultDescription`withSiteKey(string)`from configGoogle reCAPTCHA v2 site key`withId(string)``'g-recaptcha-{uniqid}'`Widget element ID`withTheme(RecaptchaV2Theme)``Light``Light` or `Dark``withType(RecaptchaV2Type)``Image``Image` or `Audio``withSize(RecaptchaV2Size)``Normal``Normal`, `Compact`, or `Invisible``withJsApiUrl(string)`Google CDNCustom JS API URL`withCallback(string)`—JavaScript callback on success`withExpiredCallback(string)`—JavaScript callback on expiry`withErrorCallback(string)`—JavaScript callback on error### reCAPTCHA v3

[](#recaptcha-v3)

The reCAPTCHA token is fetched on form submit (not on page load), preventing unexpected challenge popups:

```
use Yiisoft\FormModel\FormModel;
use YiiRocks\Recaptcha\RecaptchaV3Field;
use YiiRocks\Recaptcha\RecaptchaV3Badge;

echo RecaptchaV3Field::field($form, 'captcha')
    ->withAction('login')
    ->withFormId('login-form')
    ->withBadge(RecaptchaV3Badge::Hidden)
    ->render();
```

Available options:

MethodDefaultDescription`withSiteKey(string)`from configGoogle reCAPTCHA v3 site key`withAction(string)``''`Action name sent to Google (must match the rule's `action` if set)`withFormId(string)`—Explicit form ID (auto-resolved via `closest("form")` if omitted)`withBadge(RecaptchaV3Badge)``BottomRight``BottomRight`, `BottomLeft`, or `Hidden``withJsApiUrl(string)`Google CDNCustom JS API URL`withTranslator(?TranslatorInterface)`from registryTranslator for the hidden badge legal notice`withExecuteTimeout(?int)``15000` (ms)Fallback form submission timeout (null = disabled)**Inherited from `InputField`:**

- `->name(string)` — override the hidden input name (default: auto-derived from form model as `FormName[attribute]`)
- `->inputId(?string)` — override the hidden input ID (default: auto-generated unique ID)

**Container (inherited from `BaseField`):**

- `->containerTag(string)` — wrapper tag (default: `div`)
- `->containerClass(string ...)` — wrapper CSS class(es) (default: `mb-3`)
- `->useContainer(bool)` — enable/disable wrapper (default: `true`)
- `->containerAttributes(array)` — set all wrapper attributes
- `->addContainerAttributes(array)` — merge additional wrapper attributes

> **Hidden badge:** When `Badge::Hidden` is selected, the legal notice text ("This site is protected by reCAPTCHA…") is displayed automatically and translated when a translator is available (either via `withTranslator()` or through `RecaptchaRegistry`).

### Server-side validation

[](#server-side-validation)

#### v2

[](#v2)

```
use YiiRocks\Recaptcha\RecaptchaV2Rule;

final class ContactForm
{
    #[RecaptchaV2Rule]
    public string $gRecaptchaResponse = '';
}
```

#### v3

[](#v3)

```
use YiiRocks\Recaptcha\RecaptchaV3Rule;

final class LoginForm
{
    #[RecaptchaV3Rule(
        threshold: 0.5,
        action: 'login',
    )]
    public string $gRecaptchaResponse = '';
}
```

> **Important:** If you set `->withAction('...')` on the field, you must also set `action: '...'` on the rule with the same value. Otherwise Google will return a different action and validation will fail with "The CAPTCHA action does not match." If neither is set, no action is sent and the check is skipped entirely.

v3 rule parameterDefaultDescription`threshold``0.5`Minimum score (0.0 – 1.0)`action``null`Expected action name (skipped if `null`)`message``'The CAPTCHA verification failed.'`Error message (translatable)`scoreTooLowMessage``'The CAPTCHA score is too low.'`Error when score is below threshold`actionMismatchMessage``'The CAPTCHA action does not match.'`Error when action doesn't match`secret``null`Custom secret (uses config default if `null`)`sendRemoteIp``false`Whether to include the user's IP in verificationLicense
-------

[](#license)

MIT. See [LICENSE.md](LICENSE.md).

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance97

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

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 ~7 days

Total

4

Last Release

24d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1957a3dc890165f142079565dc6b0ef59c26838a36fba5f052985e34612ce269?d=identicon)[mr42](/maintainers/mr42)

---

Top Contributors

[![Mister-42](https://avatars.githubusercontent.com/u/68641750?v=4)](https://github.com/Mister-42 "Mister-42 (18 commits)")

---

Tags

validatorrecaptchaspamcaptchaextensionwidgetyiibotyii3

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yiirocks-recaptcha/health.svg)

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

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k16](/packages/tempest-framework)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[cakephp/cakephp

The CakePHP framework

8.8k19.5M1.8k](/packages/cakephp-cakephp)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

36789.4k2](/packages/telnyx-telnyx-php)[laminas/laminas-validator

Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria

16048.2M222](/packages/laminas-laminas-validator)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)

PHPackages © 2026

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