Download the PHP package rafalmasiarek/captcha without Composer
On this page you can find all versions of the php package rafalmasiarek/captcha. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download rafalmasiarek/captcha
More information about rafalmasiarek/captcha
Files in rafalmasiarek/captcha
Package captcha
Short Description Universal CAPTCHA verification for PHP: Google reCAPTCHA (v2/v3), Cloudflare Turnstile, and hCaptcha behind one Strategy-pattern facade. Built on rafalmasiarek/http-client.
License MIT
Informations about the package captcha
php-captcha
Universal CAPTCHA verification for PHP: Google reCAPTCHA (v2/v3), Cloudflare Turnstile, and hCaptcha behind one Strategy-pattern facade. Built on rafalmasiarek/http-client — no provider-specific SDK, no cURL/Guzzle dependency of its own.
License
Authors
Why
reCAPTCHA, Turnstile, and hCaptcha all speak a near-identical "siteverify" protocol: POST a secret key + the client-submitted token (+ optionally the user's IP) to a fixed endpoint, get back {success, ...} as JSON. Turnstile and hCaptcha deliberately mirror reCAPTCHA's wire format for drop-in compatibility.
Captcha is the one class that speaks this protocol — its constructor and verify() signature never change based on which provider is configured. Switching providers means swapping one constructor argument (a CaptchaProviderInterface); nothing else in your code changes, including how you read errors — see "Provider-agnostic error categories" below.
Deliberately out of scope: widget rendering (script URLs, data-* attributes, the client-side form field name). That differs per provider and per consuming framework/template engine, so it belongs to the caller — this library only covers server-side verification.
Namespace layout
rafalmasiarek\Captcha\*—Captchaitself,CaptchaProviderInterface,CaptchaResult,CaptchaErrorCategory,RemoteIpProviderInterface/SystemRemoteIpProvider, and the exception hierarchy. Knows the siteverify protocol shape, but no specific vendor by name.rafalmasiarek\Captcha\Provider\*— the three built-in providers (RecaptchaProvider,TurnstileProvider,HCaptchaProvider), each one's own fully self-contained error-code enum (RecaptchaErrorCode,TurnstileErrorCode,HCaptchaErrorCode), andCaptchaWidgetDescriptor(raw widget metadata — see below). These are the only classes that know a vendor's name, endpoint, or exact error-code vocabulary. Each provider builds its own widget descriptor(s) directly — nothing central to edit when adding a new one.rafalmasiarek\Captcha\Helpers\*— entirely optional widget-rendering helpers (see below). Verification itself (endpoint()/secretKey()/extraParams()/classifyErrorCode()) never depends on this namespace.- An entirely custom provider that doesn't follow the siteverify protocol at all implements
CaptchaVerifierInterfacedirectly, bypassingCaptcha/CaptchaProviderInterfaceentirely.
Install
Usage
$http and $remoteIp: override what you need, sensible defaults otherwise
Both follow the same "explicit override, zero-config fallback" shape:
rafalmasiarek/real-ip-resolver's RealIpResolver resolves the real client IP behind trusted reverse proxies, but doesn't implement RemoteIpProviderInterface directly (different method name/return type) — bridge it with a one-line adapter:
Provider-specific extras live on the provider, not on Captcha
A capability only one provider has is a method on its provider class — Captcha::verify() never changes shape to accommodate it:
reCAPTCHA v3 / hCaptcha Enterprise score and action thresholds
$result->success folds in every configured threshold check alongside the provider's own verdict, so a caller only ever needs to check one field. Fails closed: once minScore/expectedAction/expectedHostname is configured, a response that omits that field (or returns it as the wrong type) does not satisfy the check — it never silently passes just because the provider/mode didn't return it. Leave the corresponding parameter null for a provider/mode that genuinely never returns it (reCAPTCHA v2, Turnstile, standard hCaptcha) rather than configuring a check that can never pass.
minScore is validated at construction time (must be finite, within [0.0, 1.0]); expectedAction/expectedHostname must not be empty strings. A malformed response — score/action/hostname present but the wrong type, or score outside [0.0, 1.0], or success present but not a boolean — throws CaptchaResponseException rather than being silently coerced; challenge_ts is the one exception, coerced leniently since it's purely informational and never factors into $result->success.
Provider-agnostic error categories
This is the point of the whole design: CaptchaResult::$errorCategories uses the same enum no matter which provider produced the result, so your error-handling/stats/debug code never changes when you swap providers.
CaptchaResult::$errorCodes still carries the raw, provider-specific strings (e.g. "timeout-or-duplicate") for anyone who wants that level of detail — map them through the concrete provider's own enum (RecaptchaErrorCode::tryFrom(), etc., under Provider\) when you know which provider you're using.
CaptchaResult::toDebugArray() returns a flat, stable-shaped array (success, score, action, error_codes, error_categories, challenge_ts, hostname) ready for a log context (Bugsnag, PSR-3) — identical keys regardless of provider.
$raw: nothing is ever lost
CaptchaResult::$raw is the full decoded JSON response — reach into it for a provider-specific field the DTO doesn't name, e.g. Turnstile's cdata/metadata or hCaptcha's credit/score_reason.
Error handling
Two independent axes:
- Did the call itself fail? (
CaptchaVerificationExceptionand its subtypesCaptchaTimeoutException/CaptchaTransportException— both carry$transportInfo, a snapshot ofHttpResponseInterface::getInfo()for diagnostics — andCaptchaResponseException, which carries$statusCode.) A network/parsing problem, never thrown for a legitimately rejected token. - Why was a token rejected?
CaptchaResult::$errorCategories(provider-agnostic) and$errorCodes(raw) — a normal, successfully-completed call that reportssuccess: false.
Timeout detection checks HttpResponseInterface::getErrorKind() === TransportErrorKind::Timeout — a structured classification rafalmasiarek/http-client computes from curl's own error code, not a string match against getError()'s free-text message.
Optional widget-rendering helpers
Verification stays provider-agnostic and renders nothing — but a small, genuinely optional Helpers\ layer ships alongside it for the common case of actually drawing the widget, mirroring the pattern used by rafalmasiarek/csrf-token's own Helpers\. HtmlHelper holds no provider knowledge at all — it only ever reads generic data off CaptchaWidgetDescriptor.
Provider\CaptchaWidgetDescriptor— pure data (strings/arrays, no closures): script URL, CSS class, token field name, plus four generic, always-additive extension points any provider can fill in as needed —scriptUrlParams(extra query params on the script URL),extraCssClasses/extraAttributes(on the widget element — always applied, visible or invisible, no silently-ignored combination),extraHiddenFields(extra hidden inputs),extraJs(extra inline JS, appended after the base glue, each entry a complete, independent statement). Attribute/field names and CSS classes are validated at construction time — an unsafe name (e.g. anon*handler, or one ofHtmlHelper's own reserved attributes) throws\InvalidArgumentExceptionimmediately rather than silently rendering. Each provider builds its own:RecaptchaProvider::widgetV2()/::widgetV3(),TurnstileProvider::widget(),HCaptchaProvider::widget(). Adding a new provider needs no change outside its own file — not even here.Helpers\HtmlHelper— template-engine-agnostic:widget()/scripts()return plain HTML strings. Zero dependency on any template engine, any CSS framework, or any JS minifier; call it directly from raw PHP.Helpers\Twig\CaptchaExtension— Twig extension exposingcaptcha_widget()/captcha_scripts()Twig functions.Helpers\Blade\CaptchaBlade::register($bladeCompiler)— registers@captchaWidget(...)/@captchaScripts(...)Blade directives.Helpers\Plates\CaptchaExtension::register($engine)— registerscaptcha_widget()/captcha_scripts()Plates template functions.
None of Twig/Laravel/Plates is declared anywhere in composer.json — not even in suggest — matching rafalmasiarek/csrf-token's own convention exactly. These classes are never autoloaded unless a consumer actually references them, so the corresponding package is never required just because the file exists; a consumer who wants one of these helpers already has that template engine in their own project.
Placeholder tokens in scriptUrlParams/extraJs
A provider's widget() method can reference the caller's eventual site key/action/instance id without knowing them yet, via tokens substituted by HtmlHelper at render time:
| Token | Context | Form |
|---|---|---|
__CAPTCHA_SITE_KEY__ |
scriptUrlParams only |
raw, URL-encoded |
__CAPTCHA_ACTION__ |
scriptUrlParams only |
raw, URL-encoded |
__CAPTCHA_SITE_KEY_JS__ |
extraJs only |
JSON-encoded, <script>-safe |
__CAPTCHA_ACTION_JS__ |
extraJs only |
JSON-encoded, <script>-safe |
__CAPTCHA_INSTANCE_ID_JS__ |
extraJs only |
JSON-encoded, <script>-safe |
The __CAPTCHA_...___ shape (not {name}) is deliberate: it can't collide with ordinary JS object/block syntax, so an unrecognized or wrong-context token (a typo, or a JS token used inside scriptUrlParams) throws \InvalidArgumentException instead of silently passing through as garbage. JSON encoding for the _JS forms uses JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT — a value containing </script> or <script> can never prematurely terminate the surrounding <script> element.
Multiple widgets on one page
Pass the same $instanceId to both the widget() and scripts() call for one widget, and a distinct one per widget when rendering more than one:
Every DOM lookup is scoped by [data-captcha-instance="..."], and the default successCallback/expiredCallback window-global names are derived from $instanceId (captchaSuccess_<id>/captchaExpired_<id>) — two widgets never collide, even with every other parameter left at its default. $instanceId must match /^[a-zA-Z0-9_-]+$/; the single-widget-per-page case needs no $instanceId at all (defaults to 'default').
Styling feedback — no CSS framework assumed
A visible widget's scripts() output never touches a submit button's disabled state (that stays entirely the host application's call) — instead it gates the form's submit event directly, and toggles a plain .captcha-invalid class on the widget element plus hidden on an adjacent .captcha-feedback element (role="alert", aria-live="assertive", linked via aria-describedby). Style both however you like; nothing here assumes Bootstrap or any other framework. The feedback text is a plain parameter, not hardcoded English:
Content Security Policy
scripts() takes an optional $nonce, applied to both the vendor <script src="..."> tag and the inline glue <script> tag:
You still need to allow the provider's own script domain (www.google.com, challenges.cloudflare.com, js.hcaptcha.com) in your script-src directive — a nonce on your own tags doesn't relax that. Different providers' widgets may make further same-origin/frame-ancestors demands of their own (e.g. frame-src); consult each vendor's own CSP guidance. 'unsafe-inline' is never the answer this library suggests.
Reacting to a client-side failure: the captcha:error event
A provider's own glue JS can fail client-side in ways the server never sees — a timeout waiting for the widget's own .execute()-style call, that call rejecting, or an unexpected exception (currently emitted by RecaptchaProvider::widgetV3()'s invisible-widget flow; any provider's extraJs can dispatch the same event the same way). Rather than this library deciding how your app should surface that, it dispatches one generic, bubbling CustomEvent:
It's dispatched on the <form> element with bubbles: true, so one listener on document catches it for every widget on the page — no per-widget wiring needed. This is the one, generic hook; bridging it into your own error-reporting system (Bugsnag, Sentry, a homegrown one) is a few lines in your own JS, not something this library needs to know about:
Adding a new provider
A new provider is self-contained — nothing outside its own file(s) needs editing:
Provider\MyProvider implements CaptchaProviderInterface— verification (endpoint()/secretKey()/extraParams()/classifyErrorCode()/defaultTokenFieldName()), plus awidget()(orwidgetX()per variant, likeRecaptchaProvider) static method returning aCaptchaWidgetDescriptor.Provider\MyProviderErrorCode— that provider's own raw error-code enum, consumed only byMyProvider::classifyErrorCode().
That's it — always just those 2 files. A provider needing more than the generic declarative flow (official script + data-sitekey div) doesn't need a 3rd file or any new concept: it fills in CaptchaWidgetDescriptor's extraJs/scriptUrlParams/etc. directly in its own widget() method, using the placeholder tokens above. RecaptchaProvider::widgetV3() is the one built-in example — reCAPTCHA v3 has no checkbox (widgetCssClass: null) and must call grecaptcha.execute() itself, so its entire glue lives in extraJs, using __CAPTCHA_SITE_KEY_JS__/__CAPTCHA_ACTION_JS__/__CAPTCHA_INSTANCE_ID_JS__.
HtmlHelper and every template-engine wrapper consume CaptchaWidgetDescriptor generically — they never enumerate providers, so none of them needs touching.
Plain PHP — no template engine at all
HtmlHelper is just two static methods returning strings; nothing about it requires Twig/Blade/Plates or any rendering framework. This is the entire integration in a bare .php view, or even built inline in a controller:
On the receiving end, read the token back out under the field name the widget itself reports — no hardcoded 'g-recaptcha-response'/'cf-turnstile-response'/'h-captcha-response' anywhere in your code:
With a template engine
Testing with official test keys
Every provider publishes a secret/site key pair that always verifies successfully, meant exactly for integration testing like this:
| Provider | Secret key |
|---|---|
| reCAPTCHA v2 | 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe |
| hCaptcha | 0x0000000000000000000000000000000000000000 |
| Turnstile | 1x0000000000000000000000000000000AA |
Index
Classes
Captcha—rafalmasiarek\CaptchaCaptchaResponseException—rafalmasiarek\CaptchaCaptchaResult—rafalmasiarek\CaptchaCaptchaTimeoutException—rafalmasiarek\CaptchaCaptchaTransportException—rafalmasiarek\CaptchaCaptchaTransportFailureException—rafalmasiarek\CaptchaCaptchaVerificationException—rafalmasiarek\CaptchaCaptchaBlade—rafalmasiarek\Captcha\Helpers\BladeHtmlHelper—rafalmasiarek\Captcha\HelpersCaptchaExtension—rafalmasiarek\Captcha\Helpers\PlatesCaptchaExtension—rafalmasiarek\Captcha\Helpers\TwigCaptchaWidgetDescriptor—rafalmasiarek\Captcha\ProviderHCaptchaProvider—rafalmasiarek\Captcha\ProviderRecaptchaProvider—rafalmasiarek\Captcha\ProviderTurnstileProvider—rafalmasiarek\Captcha\ProviderSystemRemoteIpProvider—rafalmasiarek\Captcha
Interfaces
CaptchaProviderInterface—rafalmasiarek\CaptchaCaptchaVerifierInterface—rafalmasiarek\CaptchaRemoteIpProviderInterface—rafalmasiarek\Captcha
Enums
CaptchaErrorCategory—rafalmasiarek\CaptchaHCaptchaErrorCode—rafalmasiarek\Captcha\ProviderRecaptchaErrorCode—rafalmasiarek\Captcha\ProviderTurnstileErrorCode—rafalmasiarek\Captcha\Provider
Captcha
final class — rafalmasiarek\Captcha\Captcha · source
Verifies a CAPTCHA token against any provider that follows the "siteverify" wire protocol (reCAPTCHA, Turnstile, hCaptcha, and anything else shaped the same way) — parametrized entirely by a CaptchaProviderInterface, so this class's own constructor and verify() signature never change based on which provider is configured. Only the CaptchaProviderInterface implementation you construct changes. $http and the default $remoteIp resolver are optional overrides: omit either to get a zero-config default (CurlHttpClient+SystemDnsResolver; SystemRemoteIpProvider's naive $_SERVER['REMOTE_ADDR']) — the same "explicit override, sensible fallback" shape verify()'s own $remoteIp parameter already has. Logs short, dot-namespaced events ("captcha.verify.ok"/".rejected"/ ".timeout"/".transport_error"/".invalid_response") to an optional PSR-3 logger — rejections and failures always log; successes only when $audit is true, matching rafalmasiarek/dns-resolver's FailoverDnsClient. $container identifies this instance in that log output (e.g. "contactform_main", "login") when an app configures more than one Captcha, mirroring this app's own CSRF module's "container" concept — never sent to the provider, purely a local log/debug label.
implements CaptchaVerifierInterface
Depends on: RemoteIpProviderInterface, HttpClientInterface, LoggerInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$logger |
LoggerInterface |
private readonly | — |
$http |
HttpClientInterface |
private readonly | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
provider() |
public | CaptchaProviderInterface |
The provider this instance verifies against — e.g. for a caller that wants to discover CaptchaProviderInterface::defaultTokenFieldName() without hardcoding any vendor's convention itself. |
verify() |
public | CaptchaResult |
— |
extractScore() |
private | float\|null |
— |
extractStringField() |
private | string\|null |
— |
extractErrorCodes() |
private | list<string> |
— |
logInvalidResponse() |
private | void |
— |
resolveIp() |
private | string\|null |
Resolves the IP to send, in order: an explicit per-call value, the Captcha-bound default, then the naive system fallback. Whatever the source, the result is validated as a real IPv4/IPv6 address — an invalid value (empty, malformed, stray whitespace) is treated as no IP at all rather than sent to the provider as-is. |
log() |
private | void |
— |
__construct()
#### `Captcha __construct()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L71)
| Param | Type | Description |
|---|---|---|
| `$provider` | [`CaptchaProviderInterface`](#captchaproviderinterface) | — |
| `$defaultIpProvider` | `RemoteIpProviderInterface\|null` | Used when verify() isn't given its own $remoteIp. Falls back to SystemRemoteIpProvider when also null. |
| `$http` | `HttpClientInterface\|null` | Falls back to CurlHttpClient(SystemDnsResolver()) when null. |
| `$timeout` | `float` | Request timeout in seconds. |
| `$minScore` | `float\|null` | Minimum accepted score, inclusive, in [0.0, 1.0] (null = do not check). Fails closed: a response missing a score (or returning one out of range) does NOT satisfy this check once configured, regardless of what the provider/mode normally returns — a legitimate provider/mode without scores should leave this null rather than configure one that can never pass. |
| `$expectedAction` | `string\|null` | Expected action value (null = do not check). Fails closed the same way as $minScore when configured. |
| `$expectedHostname` | `string\|null` | Expected "hostname" field (null = do not check). Fails closed the same way when configured. |
| `$container` | `string\|null` | Local label identifying this instance in log output — e.g. "contactform_main", "login" — when an app configures more than one Captcha. Never sent to the provider. |
| `$logger` | `LoggerInterface\|null` | Receives rejection/failure warnings/errors always, and (when $audit is true) a debug entry for every successful verification. Defaults to a no-op logger. |
| `$audit` | `bool` | Whether to also log successful verifications (debug level). |
| Throws | When |
|---|---|
| `\InvalidArgumentException` | When $minScore is outside [0.0, 1.0], or $expectedAction/ $expectedHostname is an empty string. |
provider()
#### `Captcha provider()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L103)
The provider this instance verifies against — e.g. for a caller that wants to discover CaptchaProviderInterface::defaultTokenFieldName() without hardcoding any vendor's convention itself.
**Returns:** [`CaptchaProviderInterface`](#captchaproviderinterface)
verify()
#### `Captcha verify()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L111)
| Param | Type | Description |
|---|---|---|
| `$token` | `string` | The token the client submitted (e.g. "g-recaptcha-response", "cf-turnstile-response", or "h-captcha-response" form field). |
| `$remoteIp` | `string\|RemoteIpProviderInterface\|null` | The end user's real IP address (post-trusted-proxy-resolution — e.g. from rafalmasiarek/real-ip-resolver's RealIpResolver, not a raw $_SERVER['REMOTE_ADDR']), as a string, or an object that resolves it lazily via RemoteIpProviderInterface. Optional — omitting it uses whatever default the implementation falls back to. |
**Returns:** [`CaptchaResult`](#captcharesult)
| Throws | When |
|---|---|
| [`CaptchaTimeoutException`](#captchatimeoutexception) | When the provider doesn't respond within the timeout. |
| [`CaptchaTransportException`](#captchatransportexception) | On any other transport failure. |
| [`CaptchaResponseException`](#captcharesponseexception) | When the response body isn't valid JSON. |
extractScore()
#### `Captcha extractScore()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L223)
| Param | Type | Description |
|---|---|---|
| `$data` | `arrayextractStringField()
#### `Captcha extractStringField()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L251)
| Param | Type | Description |
|---|---|---|
| `$data` | `arrayextractErrorCodes()
#### `Captcha extractErrorCodes()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L274)
| Param | Type | Description |
|---|---|---|
| `$data` | `arraylogInvalidResponse()
#### `Captcha logInvalidResponse()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L304)
| Param | Type | Description |
|---|---|---|
| `$statusCode` | `int` | — |
| `$field` | `string` | — |
resolveIp()
#### `Captcha resolveIp()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L320)
Resolves the IP to send, in order: an explicit per-call value, the Captcha-bound default, then the naive system fallback. Whatever the source, the result is validated as a real IPv4/IPv6 address — an invalid value (empty, malformed, stray whitespace) is treated as no IP at all rather than sent to the provider as-is.
| Param | Type | Description |
|---|---|---|
| `$remoteIp` | `string\|RemoteIpProviderInterface\|null` | — |
**Returns:** `string\|null`
log()
#### `Captcha log()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Captcha.php#L346)
| Param | Type | Description |
|---|---|---|
| `$level` | `string` | PSR-3 log level. |
| `$message` | `string` | Dot-namespaced event code. |
| `$context` | `arrayCaptchaErrorCategory
enum — rafalmasiarek\Captcha\CaptchaErrorCategory · source
Provider-agnostic classification of why a verification was rejected. CaptchaResult::$errorCategories always uses this enum regardless of which provider was used — a caller that reads it (e.g. for stats/debug logging) never needs to change when a different provider is configured, unlike CaptchaResult::$errorCodes, which are raw, provider-specific strings. ConfigurationError/TokenRejected/ProviderInternalError come from a provider's own CaptchaProviderInterface::classifyErrorCode() (each provider maps its own vocabulary into this shared vocabulary). ScoreTooLow/ActionMismatch are computed by Captcha itself from the $minScore/$expectedAction checks — not something any provider's API reports directly.
| Case | Value |
|---|---|
ConfigurationError |
— |
TokenRejected |
— |
ProviderInternalError |
— |
ScoreTooLow |
— |
ActionMismatch |
— |
HostnameMismatch |
— |
Unknown |
— |
CaptchaProviderInterface
interface — rafalmasiarek\Captcha\CaptchaProviderInterface · source
Configuration + behavior for one provider that follows the "siteverify" wire protocol Captcha speaks — POST secret+response(+remoteip+extras) as form data to a fixed endpoint, get back {success, ...} as JSON. Knows only this protocol shape, not any specific vendor by name; concrete implementations (RecaptchaProvider, TurnstileProvider, HCaptchaProvider) live under the Provider\ namespace and are the ones that know a vendor. A pure, stateless-from-the-outside value object — no HTTP logic here; Captcha owns the actual request/response handling and reads this interface's five methods to do it.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
endpoint() |
public | string |
— |
defaultTokenFieldName() |
public | string |
The conventional HTML form field name this provider's widget posts its token under (e.g. "g-recaptcha-response") — a discoverable default for a caller that reads the token out of a request body, so nothing above this interface needs to hardcode any one vendor's convention. Purely informational: Captcha::verify() always takes the token value directly and never reads a request body itself. |
secretKey() |
public | string |
— |
extraParams() |
public | array<string, string> |
Additional POST fields beyond secret/response/remoteip — e.g. hCaptcha's optional "sitekey" or Turnstile's optional "idempotency_key". Empty for a provider that needs nothing extra. |
classifyErrorCode() |
public | CaptchaErrorCategory |
Classifies one of this provider's own raw error codes into the shared, provider-agnostic CaptchaErrorCategory vocabulary. |
endpoint()
#### `CaptchaProviderInterface endpoint()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaProviderInterface.php#L26)
**Returns:** `string` — Absolute URL of this provider's siteverify endpoint.
defaultTokenFieldName()
#### `CaptchaProviderInterface defaultTokenFieldName()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaProviderInterface.php#L38)
The conventional HTML form field name this provider's widget posts its token under (e.g. "g-recaptcha-response") — a discoverable default for a caller that reads the token out of a request body, so nothing above this interface needs to hardcode any one vendor's convention. Purely informational: Captcha::verify() always takes the token value directly and never reads a request body itself.
**Returns:** `string`
secretKey()
#### `CaptchaProviderInterface secretKey()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaProviderInterface.php#L43)
**Returns:** `string` — This provider's secret key.
extraParams()
#### `CaptchaProviderInterface extraParams()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaProviderInterface.php#L52)
Additional POST fields beyond secret/response/remoteip — e.g. hCaptcha's optional "sitekey" or Turnstile's optional "idempotency_key". Empty for a provider that needs nothing extra.
**Returns:** `arrayclassifyErrorCode()
#### `CaptchaProviderInterface classifyErrorCode()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaProviderInterface.php#L62)
Classifies one of this provider's own raw error codes into the shared, provider-agnostic CaptchaErrorCategory vocabulary.
| Param | Type | Description |
|---|---|---|
| `$rawCode` | `string` | A value from the provider's "error-codes" response field. |
**Returns:** [`CaptchaErrorCategory`](#captchaerrorcategory)
CaptchaResponseException
class — rafalmasiarek\Captcha\CaptchaResponseException · source
Thrown when the provider responded, but the response body wasn't valid JSON or wasn't a JSON object — the HTTP request itself succeeded, but its content can't be interpreted (e.g. the provider returned an HTML error page instead of JSON, often alongside a non-2xx $statusCode).
extends CaptchaVerificationException
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
__construct()
#### `CaptchaResponseException __construct()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaResponseException.php#L21)
| Param | Type | Description |
|---|---|---|
| `$message` | `string` | — |
| `$statusCode` | `int` | HTTP status code of the response, 0 when unknown. |
CaptchaResult
final readonly class — rafalmasiarek\Captcha\CaptchaResult · source
Result of a CAPTCHA verification call. Provider-agnostic shape — every field is either universal ($success) or "present when the provider/mode happens to return it, null/empty otherwise". $errorCodes stays raw, provider-specific strings (never filtered — an unrecognized/future code is never dropped). $errorCategories is the provider-agnostic classification of the same facts, via CaptchaProviderInterface::classifyErrorCode() plus Captcha's own $minScore/$expectedAction checks — the field a caller's downstream error-handling/stats code should actually branch on, since it stays the same shape no matter which provider produced it. $raw always carries the full decoded response, so a provider-specific field this DTO doesn't name (Turnstile's "cdata"/"metadata", hCaptcha's "credit"/"score_reason", ...) is never lost.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
toDebugArray() |
public | array<string, mixed> |
A flat, provider-agnostic snapshot suitable for logging (e.g. as a Bugsnag/PSR-3 context array) — the same keys regardless of which provider produced this result. |
__construct()
#### `CaptchaResult __construct()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaResult.php#L41)
| Param | Type | Description |
|---|---|---|
| `$success` | `bool` | Whether verification passed overall — the provider accepted the token AND (when configured) the score/action checks passed. |
| `$score` | `float\|null` | Confidence score (0.0-1.0), when the provider/mode returns one. |
| `$action` | `string\|null` | The action name the token was issued for, when the provider/mode returns one. |
| `$errorCodes` | `listtoDebugArray()
#### `CaptchaResult toDebugArray()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaResult.php#L60)
A flat, provider-agnostic snapshot suitable for logging (e.g. as a Bugsnag/PSR-3 context array) — the same keys regardless of which provider produced this result.
**Returns:** `arrayCaptchaTimeoutException
class — rafalmasiarek\Captcha\CaptchaTimeoutException · source
Thrown when the provider's siteverify endpoint did not respond within the configured timeout. Detection checks HttpResponseInterface::getErrorKind() === TransportErrorKind::Timeout — a structured classification based on curl's own error code (CURLE_OPERATION_TIMEDOUT), not a string match against the free-text getError() message. A transport failure that isn't a timeout is thrown as the less specific CaptchaTransportException instead.
extends CaptchaTransportFailureException
CaptchaTransportException
class — rafalmasiarek\Captcha\CaptchaTransportException · source
Thrown when the provider's siteverify endpoint could not be reached at all — DNS failure, connection refused, TLS failure, a block_private_network refusal — for any transport failure not recognized as a timeout (see CaptchaTimeoutException).
extends CaptchaTransportFailureException
CaptchaTransportFailureException
abstract class — rafalmasiarek\Captcha\CaptchaTransportFailureException · source
Base type for CaptchaTimeoutException/CaptchaTransportException — both carry a snapshot of the failed call's transport diagnostics, for a caller that wants to log them (e.g. alongside a Bugsnag report) without having had access to the underlying HttpResponseInterface itself.
extends CaptchaVerificationException
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
__construct()
#### `CaptchaTransportFailureException __construct()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaTransportFailureException.php#L24)
| Param | Type | Description |
|---|---|---|
| `$message` | `string` | — |
| `$transportInfo` | `arrayCaptchaVerificationException
class — rafalmasiarek\Captcha\CaptchaVerificationException · source
Base type for every exception thrown when a verification call itself fails — never for a legitimate "the token was rejected" outcome, which is a normal CaptchaResult with success=false (see CaptchaResult::$errorCodes and CaptchaResult::$errorCategories for why it was rejected). Thrown directly only when no more specific subtype applies; prefer catching CaptchaTimeoutException / CaptchaTransportException / CaptchaResponseException when the distinction matters, or this base type to catch all of them at once.
extends \RuntimeException
CaptchaVerifierInterface
interface — rafalmasiarek\Captcha\CaptchaVerifierInterface · source
Verifies a CAPTCHA token server-side. One interface for every provider — reCAPTCHA, Cloudflare Turnstile, hCaptcha all speak a near-identical token-verification protocol, so a consumer (a login brute-force guard, a contact form validator, ...) can depend on this interface alone. Captcha is the one general-purpose implementation, parametrized by a CaptchaProviderInterface. A caller with an entirely custom provider that doesn't follow the siteverify protocol at all implements this interface directly instead, bypassing Captcha/CaptchaProviderInterface entirely. Deliberately does not cover widget rendering (script URL, data-* attributes, the form field name the client posts the token under) — that differs per provider and per consuming framework, so it belongs to the caller, not here.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
verify() |
public | CaptchaResult |
— |
verify()
#### `CaptchaVerifierInterface verify()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/CaptchaVerifierInterface.php#L43)
| Param | Type | Description |
|---|---|---|
| `$token` | `string` | The token the client submitted (e.g. "g-recaptcha-response", "cf-turnstile-response", or "h-captcha-response" form field). |
| `$remoteIp` | `string\|RemoteIpProviderInterface\|null` | The end user's real IP address (post-trusted-proxy-resolution — e.g. from rafalmasiarek/real-ip-resolver's RealIpResolver, not a raw $_SERVER['REMOTE_ADDR']), as a string, or an object that resolves it lazily via RemoteIpProviderInterface. Optional — omitting it uses whatever default the implementation falls back to. |
**Returns:** [`CaptchaResult`](#captcharesult)
| Throws | When |
|---|---|
| [`CaptchaTimeoutException`](#captchatimeoutexception) | When the provider doesn't respond within the timeout. |
| [`CaptchaTransportException`](#captchatransportexception) | On any other transport failure. |
| [`CaptchaResponseException`](#captcharesponseexception) | When the response body isn't valid JSON. |
CaptchaBlade
final class — rafalmasiarek\Captcha\Helpers\Blade\CaptchaBlade · source
Blade helper registering @captchaWidget(...) and @captchaScripts(...) directives — each simply echoes the corresponding HtmlHelper call with whatever expression the template passed. No service resolution needed: unlike a stateful service, HtmlHelper's methods take plain arguments (a CaptchaWidgetDescriptor + strings), nothing to resolve from a container. Usage: \rafalmasiarek\Captcha\Helpers\Blade\CaptchaBlade::register($bladeCompiler); Template usage:
| Method | Visibility | Returns | Summary |
|---|---|---|---|
register() |
public static | void |
— |
register()
#### `CaptchaBlade register()`
[source](https://github.com/rafalmasiarek/php-captcha/blob/main/src/Helpers/Blade/CaptchaBlade.php#L33)
| Param | Type | Description |
|---|---|---|
| `$bladeCompiler` | `object` | Instance of Illuminate\View\Compilers\BladeCompiler. |
| Throws | When |
|---|---|
| `\InvalidArgumentException` | When $bladeCompiler doesn't support directive(). |
HtmlHelper
final class — rafalmasiarek\Captcha\Helpers\HtmlHelper · source
Template-engine-agnostic HTML/JS helper for rendering a CAPTCHA widget. Holds no provider knowledge — takes a CaptchaWidgetDescriptor built by the Provider class in use (e.g. RecaptchaProvider::widgetV2()). Framework wrappers (e.g. Helpers\Twig\CaptchaExtension) delegate here; usable directly with no template engine. $instanceId correlates one widget()/scripts() pair so multiple widgets on the same page never share DOM lookups or window-global callback names — pass the SAME $instanceId to both calls for one widget; pass a distinct one per widget when rendering more than one on a page. The 'default' default covers the common single-widget-per-page case with zero config. No CSS framework assumptions: feedback is a plain .captcha-feedback element (role="alert", aria-live), toggled via a .captcha-invalid class on the widget element — style both however your app likes. Nothing here disables a submit button; it gates the form's submit event instead, so disabled-state ownership always stays with the host application.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
widget() |
public static | string |
Widget markup: a div with a checkbox (widgetCssClass set) or a hidden input (widgetCssClass null), plus extraCssClasses/extraAttributes/ extraHiddenFields. A visible widget also gets an adjacent, initially hidden feedback element (role="alert") toggled by scripts()'s glue JS. |
scripts() |
public static | string |