PHP code example of gkcaptcha / gkcaptcha-php

1. Go to this page and download the library: Download gkcaptcha/gkcaptcha-php 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/ */

    

gkcaptcha / gkcaptcha-php example snippets


use GkCaptcha\GkCaptchaClient;

$client = new GkCaptchaClient(
    secretKey: $_ENV['GKCAPTCHA_SECRET_KEY'],
    siteKey:   $_ENV['GKCAPTCHA_SITE_KEY'],
);

$result = $client->verifyToken($request->input('captchaToken'));

if (!$result->success) {
    return response()->json(['error' => 'CAPTCHA verification failed'], 403);
}

$result = $client->verifyToken($token);

if ($result->failOpen) {
    // Network error — request allowed through (fail-open policy)
    // Log a warning, monitor for sustained failures
}

$client = new GkCaptchaClient(
    secretKey:  $_ENV['GKCAPTCHA_SECRET_KEY'],
    siteKey:    $_ENV['GKCAPTCHA_SITE_KEY'],
    failClosed: true,
);

try {
    $result = $client->verifyToken($token);
} catch (\GkCaptcha\GkCaptchaException $e) {
    // Network error — request blocked (fail-closed policy)
    return response()->json(['error' => 'Verification unavailable'], 503);
}

public function verifyToken(
    string $token,
    ?string $clientIP  = null,
    ?string $userAgent = null,
): VerifyTokenResponse

use GkCaptcha\ReasonCode;

if ($result->reasonCode === ReasonCode::TokenExpired->value) {
    // Handle expired token
}

// In a form request or controller:
use GkCaptcha\GkCaptchaClient;

$client = new GkCaptchaClient(
    secretKey: config('services.gatekeeper.secret'),
    siteKey:   config('services.gatekeeper.site_key'),
);

$result = $client->verifyToken($request->captchaToken, $request->ip(), $request->userAgent());

if (!$result->success) {
    abort(403, 'CAPTCHA verification failed');
}
bash
composer 
bash
# Install dev dependencies (phpunit/phpunit ^10)
composer install

# Run tests (n