PHP Integration

Zero-dependency PHP integration patterns for token verification. Requires PHP 8.1+.

Copy these patterns into your project to integrate gkCAPTCHA server-side verification.

Installation

terminal
composer require gkcaptcha/gkcaptcha-php

Zero Composer runtime dependencies. Requires PHP 8.1+.

Quick Start

verify.php
use GkCaptcha\GkCaptchaClient;

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

$result = $client->verifyToken($_POST['captchaToken']);

if (!$result->success) {
    http_response_code(403);
    echo json_encode(['error' => 'CAPTCHA verification failed']);
    exit;
}

Form Handling

Plain PHP form handling with client IP and User-Agent forwarding for binding verification.

form.php
<?php
use GkCaptcha\GkCaptchaClient;

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['captchaToken'] ?? '';
    $result = $client->verifyToken($token, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);

    if (!$result->success) {
        http_response_code(403);
        die('CAPTCHA verification failed');
    }

    // Process form...
}
?>

Response Shape

response.php
// VerifyTokenResponse properties
$result->success;    // bool   - true if verification passed
$result->score;      // float  - risk score 0.0 (human) to 1.0 (bot)
$result->timestamp;  // int    - Unix timestamp when token was issued
$result->error;      // ?string - error message on failure
$result->reasonCode; // ?string - machine-readable reason code
$result->failOpen;   // bool   - true when success due to fail-open

Error Handling

By default (fail-open), if the gkCAPTCHA API is unreachable after retries, the client returns $result->success = true, $result->failOpen = true. Set failClosed: true to throw GkCaptchaException instead.

افتراضيًا (فتح عند الفشل)، إذا كانت واجهة gkCAPTCHA غير متاحة، يُرجع العميل نجاحًا. لتغيير هذا السلوك استخدم failClosed: true.

fail_closed.php
$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)
    http_response_code(503);
    echo json_encode(['error' => 'Verification unavailable']);
    exit;
}

Environment Variables

VariableRequiredDescription
GKCAPTCHA_SECRET_KEYYesSecret key from gatekeeper.sa dashboard
GKCAPTCHA_SITE_KEYYesSite key from gatekeeper.sa dashboard
GKCAPTCHA_API_URLNoOverride API URL (default: https://gkcaptcha.gatekeeper.sa)