PHP code example of rafalmasiarek / captcha

1. Go to this page and download the library: Download rafalmasiarek/captcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rafalmasiarek / captcha example snippets


use rafalmasiarek\Captcha\Captcha;
use rafalmasiarek\Captcha\Provider\RecaptchaProvider;
use rafalmasiarek\Captcha\Provider\TurnstileProvider;
use rafalmasiarek\Captcha\Provider\HCaptchaProvider;
use rafalmasiarek\Captcha\CaptchaTimeoutException;
use rafalmasiarek\Captcha\CaptchaTransportException;
use rafalmasiarek\Captcha\CaptchaResponseException;

// Provider-specific arguments live ONLY on the provider object.
$provider = new RecaptchaProvider($secretKey);
// or: new TurnstileProvider($secretKey);
// or: new HCaptchaProvider($secretKey, siteKey: $siteKey);

// Captcha's constructor is IDENTICAL regardless of which provider you pass.
$captcha = new Captcha($provider);

try {
    $result = $captcha->verify($tokenFromClient, $remoteIp);
} catch (CaptchaTimeoutException $e) {
    // the provider didn't respond within the timeout — $e->transportInfo has dns/connect/tls/total timing
} catch (CaptchaTransportException $e) {
    // couldn't reach the provider at all (DNS, connection refused, TLS, ...) — $e->transportInfo too
} catch (CaptchaResponseException $e) {
    // the provider responded, but the body wasn't valid JSON — $e->statusCode
}

if ($result->success) {
    // accepted
}

// $http: omit it to get CurlHttpClient(SystemDnsResolver()) automatically.
$captcha = new Captcha($provider, http: $myConfiguredHttpClient);

// $remoteIp: omit it on verify() to get SystemRemoteIpProvider's naive
// $_SERVER['REMOTE_ADDR'] automatically. Three levels of precedence:
$captcha->verify($token, $remoteIp);              // 1. explicit per-call value wins
$captcha = new Captcha($provider, defaultIpProvider: $resolver);  // 2. bound once, used when verify() doesn't override
// 3. SystemRemoteIpProvider — used when neither of the above is set

use rafalmasiarek\Captcha\RemoteIpProviderInterface;

final class RealIpResolverAdapter implements RemoteIpProviderInterface
{
    public function __construct(private readonly RealIpResolver $resolver) {}

    public function getRemoteIp(): ?string
    {
        $ip = $this->resolver->getIp();
        return $ip !== '' ? $ip : null;
    }
}

$captcha = new Captcha($provider, defaultIpProvider: new RealIpResolverAdapter($realIpResolver));

// Turnstile: re-verify the same token (e.g. after a retried request) without
// Cloudflare flagging it as reuse. withIdempotencyKey() returns a new provider
// instance; Captcha itself doesn't need to know this capability exists.
$provider = (new TurnstileProvider($secretKey))->withIdempotencyKey($idempotencyKey);
$captcha = new Captcha($provider);
$captcha->verify($token, $remoteIp);

$captcha = new Captcha($provider, minScore: 0.5, expectedAction: 'login', expectedHostname: 'example.com');

use rafalmasiarek\Captcha\CaptchaErrorCategory;

if (\in_array(CaptchaErrorCategory::ConfigurationError, $result->errorCategories, true)) {
    // our secret key / request is wrong — fix the integration, not a user retry
}
if (\in_array(CaptchaErrorCategory::TokenRejected, $result->errorCategories, true)) {
    // the token was legitimately rejected (expired, reused, malformed)
}
if (\in_array(CaptchaErrorCategory::ScoreTooLow, $result->errorCategories, true)) {
    // passed the provider's own check, but didn't meet $minScore (or the response omitted a score at all)
}
if (\in_array(CaptchaErrorCategory::HostnameMismatch, $result->errorCategories, true)) {
    // didn't match $expectedHostname
}

<?= HtmlHelper::widget($widgetA, $siteKeyA, instanceId: 'login-form') 

HtmlHelper::widget($widget, $siteKey, validationMessage: 'Proszę potwierdzić, że nie jesteś robotem.');

HtmlHelper::scripts($widget, $siteKey, nonce: $cspNonceForThisRequest);


use rafalmasiarek\Captcha\Helpers\HtmlHelper;
use rafalmasiarek\Captcha\Provider\TurnstileProvider;

$widget = TurnstileProvider::widget();

$token = $_POST[$widget->tokenFieldName] ?? '';
$result = $captcha->verify($token, $remoteIp);

 // with Helpers\Plates\CaptchaExtension::register($engine) called 

public function __construct(CaptchaProviderInterface $provider, ?RemoteIpProviderInterface $defaultIpProvider, ?HttpClientInterface $http, float $timeout, ?float $minScore, ?string $expectedAction, ?string $expectedHostname, ?string $container, ?LoggerInterface $logger, bool $audit)

public function provider(): CaptchaProviderInterface

public function verify(string $token, string|RemoteIpProviderInterface|null $remoteIp): CaptchaResult

private function extractScore(array $data, string $endpoint, int $statusCode): ?float

private function extractStringField(array $data, string $field, string $endpoint, int $statusCode): ?string

private function extractErrorCodes(array $data, string $endpoint, int $statusCode): array

private function logInvalidResponse(int $statusCode, string $field): void

private function resolveIp(string|RemoteIpProviderInterface|null $remoteIp): ?string

private function log(string $level, string $message, array $context): void

public function endpoint(): string

public function defaultTokenFieldName(): string

public function secretKey(): string

public function extraParams(): array

public function classifyErrorCode(string $rawCode): CaptchaErrorCategory

public function __construct(string $message, int $statusCode)

public function __construct(bool $success, ?float $score, ?string $action, array $errorCodes, array $errorCategories, ?string $challengeTs, ?string $hostname, array $raw)

public function toDebugArray(): array

public function __construct(string $message, array $transportInfo)

public function verify(string $token, string|RemoteIpProviderInterface|null $remoteIp): CaptchaResult

public static function register(object $bladeCompiler): void

public static function widget(CaptchaWidgetDescriptor $widget, string $siteKey, ?string $successCallback, ?string $expiredCallback, string $instanceId, string $validationMessage): string

public static function scripts(CaptchaWidgetDescriptor $widget, string $siteKey, string $action, ?string $successCallback, ?string $expiredCallback, string $instanceId, ?string $nonce): string

private static function assertSafeInstanceId(string $instanceId): void

private static function assertKnownTokens(string $template, array $allowed): void

private static function buildScriptUrl(CaptchaWidgetDescriptor $widget, string $siteKey, string $action): string

private static function substituteJsTokens(string $template, string $siteKey, string $action, string $instanceId): string

private static function jsonForJs(string $value): string

private static function renderExtraAttributes(CaptchaWidgetDescriptor $widget): string

private static function renderExtraHiddenFields(CaptchaWidgetDescriptor $widget): string

private static function baseGlueJs(string $successCallback, string $expiredCallback, string $instanceId): string

public static function register(Engine $engine): void

public function getFunctions(): array

public function __construct(string $scriptUrl, ?string $widgetCssClass, string $tokenFieldName, array $scriptUrlParams, array $extraCssClasses, array $extraAttributes, array $extraHiddenFields, array $extraJs)

private static function assertSafeAttributeName(string $name): void

private static function assertSafeFieldName(string $name): void

private static function assertSafeCssClass(string $class): void

public function isConfigurationError(): bool

public function isTokenRejection(): bool

public function __construct(string $secretKey, ?string $siteKey)

public function endpoint(): string

public function defaultTokenFieldName(): string

public function secretKey(): string

public function extraParams(): array

public function classifyErrorCode(string $rawCode): CaptchaErrorCategory

public static function widget(): CaptchaWidgetDescriptor

public function isConfigurationError(): bool

public function isTokenRejection(): bool

public function __construct(string $secretKey)

public function endpoint(): string

public function secretKey(): string

public function defaultTokenFieldName(): string

public function extraParams(): array

public function classifyErrorCode(string $rawCode): CaptchaErrorCategory

public static function widgetV2(): CaptchaWidgetDescriptor

public static function widgetV3(): CaptchaWidgetDescriptor

public function isConfigurationError(): bool

public function isTokenRejection(): bool

public function __construct(string $secretKey, ?string $idempotencyKey)

public function withIdempotencyKey(string $idempotencyKey): self

public function endpoint(): string

public function defaultTokenFieldName(): string

public function secretKey(): string

public function extraParams(): array

public function classifyErrorCode(string $rawCode): CaptchaErrorCategory

public static function widget(): CaptchaWidgetDescriptor

public function getRemoteIp(): ?string

public function getRemoteIp(): ?string