CaptchaNo
Back to blog
tutorials02 Dec 2026·11 min read

Solve reCAPTCHA in PHP: cURL, Guzzle and Laravel

DDishant Singh
tutorials

Solve reCAPTCHA in PHP with plain cURL: find the sitekey, request a token, submit it with the same session, and queue it in Laravel. Run on PHP 8.5.

To solve reCAPTCHA in PHP, read the page's sitekey, send it with the page URL to a solving API over cURL, and submit the returned token as g-recaptcha-response with the same cookies and user agent. No browser is needed when the target accepts a plain form POST. This guide gives you the whole flow in plain PHP, then the Guzzle and Laravel versions, and the places where it breaks. For the v2 product details see our reCAPTCHA v2 solver page.

We run CaptchaNo, so the solve step uses our API. The sitekey extraction, cookie handling and submit code work the same whichever token source you use.

What we ran, and what we didn't

We ran the PHP below on PHP 8.5.11 on 2 December 2026 (UTC), against public pages only. We did not run a real solve, because no CaptchaNo test key was available for this run, so there are no solve times or success rates in this post.

  • Sitekey extraction from Google's public reCAPTCHA v2 demo page with the cURL helper. It returned the demo sitekey 6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ- over HTTP 200.
  • The error path: we called our API with a deliberately invalid key. It returned HTTP 401 with {"error":{"code":"invalid_api_key","message":"The API key is missing or not valid."}}, and the helper below turned it into a typed exception.
  • A placeholder token posted to the demo form. Google's page answered "Please verify that you are not a robot."
  • Server-side verification with Google's published test secret. siteverify returned success: true and hostname testkey.google.com.

The Guzzle and Laravel snippets send the same request as the cURL version. We syntax-checked them but only ran the cURL code.

How the flow works in five steps

Every PHP captcha integration is the same five steps, and the token has to be spent quickly.

  1. GET the page with a cookie jar and a fixed user agent.
  2. Read the sitekey from data-sitekey.
  3. POST the sitekey, page URL and user agent to the solving API.
  4. Wait for the token (one blocking call, with polling as a fallback).
  5. POST the form with g-recaptcha-response, reusing the cookie jar, user agent and proxy.

Google's documentation says a response token is valid for two minutes and can be verified only once, per its verification guide. So solve immediately before step 5, not at the start of a long script. We explain the usual causes of rejected tokens in why captcha tokens get rejected.

Step 1: Find the sitekey and the variant

The sitekey is the data-sitekey attribute on the g-recaptcha element, or the k= parameter in the widget iframe URL. Our run found it with a one-line regular expression on Google's demo. If your regex finds nothing, the page probably renders the widget from JavaScript, loads api.js?render=KEY (v3), or uses an invisible widget. Our guides cover how to find a reCAPTCHA sitekey and how invisible reCAPTCHA differs.

Step 2: A reusable cURL helper with real error handling

One function that blocks for up to 60 seconds, falls back to polling and throws a typed exception is enough for most scripts. The request goes to POST /v1/solve?wait=60 with your key as a Bearer token, as described in the API reference. The cURL timeout must be longer than the wait, or PHP gives up before the API answers.

<?php
declare(strict_types=1);

final class CaptchaNoException extends RuntimeException
{
    public function __construct(public readonly string $apiCode, string $message, public readonly int $httpStatus = 0)
    {
        parent::__construct($message);
    }
}

function captchano_request(string $method, string $path, string $apiKey, ?array $body = null): array
{
    $ch = curl_init('https://api.captchano.com' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 75, // longer than ?wait=60
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
    }
    $raw    = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    if ($raw === false) {
        throw new CaptchaNoException('network', curl_error($ch));
    }

    $data = json_decode($raw, true);
    if (!is_array($data)) {
        throw new CaptchaNoException('bad_response', "HTTP $status, not JSON", $status);
    }
    if (isset($data['error'])) {
        $e = $data['error'];
        throw new CaptchaNoException($e['code'] ?? 'unknown', $e['message'] ?? 'API error', $status);
    }
    return $data;
}

/** Blocks until solved. Returns ['token' => ..., 'userAgent' => ...]. */
function captchano_solve(array $task, string $apiKey): array
{
    $data = captchano_request('POST', '/v1/solve?wait=60', $apiKey, $task);
    // A solve can outlast the 60 s wait: poll the task until it finishes.
    $deadline = time() + 120;
    while (in_array($data['status'] ?? '', ['queued', 'solving'], true) && time() < $deadline) {
        sleep(5);
        $data = captchano_request('GET', '/v1/task/' . rawurlencode($data['id']), $apiKey);
    }
    if (($data['status'] ?? '') !== 'ready') {
        throw new CaptchaNoException('not_ready', 'Task ended as ' . ($data['status'] ?? 'unknown'));
    }
    return $data['solution'];
}

Two details from our run. First, curl_close() is deprecated in PHP 8.5 because it has had no effect since PHP 8.0, so the helper does not call it. Our first version did and printed a deprecation notice. Second, every API error arrives as {"error":{"code":...}}, so one isset($data['error']) check covers all of them. Anything else you need from the raw API is in the docs and the cURL guide.

Step 3: Submit the token from the same session

The token only helps if the request that carries it looks like the session that loaded the page. Use one cookie jar for the GET and the POST, send the same user agent to the API and to the site, and route both through the same proxy if you use one. Replace the field names below with the ones in the target's real form.

<?php
declare(strict_types=1);
require __DIR__ . '/captchano.php';

$apiKey  = getenv('CAPTCHANO_API_KEY');
$pageUrl = 'https://example.com/login';
$ua      = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36';
$jar     = tempnam(sys_get_temp_dir(), 'jar');

function fetch(string $url, string $ua, string $jar, ?array $post = null): string
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT      => $ua,
        CURLOPT_COOKIEJAR      => $jar,   // keep the session cookie between
        CURLOPT_COOKIEFILE     => $jar,   // the GET and the POST
        CURLOPT_TIMEOUT        => 30,
        // CURLOPT_PROXY => 'http://user:pass@host:port', // same proxy as the solve
    ]);
    if ($post !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    return (string) curl_exec($ch);
}

// 1. Load the page and read the sitekey.
$html = fetch($pageUrl, $ua, $jar);
if (!preg_match('/data-sitekey="([^"]+)"/', $html, $m)) {
    exit("No data-sitekey found: check for render=, an iframe or an invisible widget.\n");
}

// 2. Solve right before you submit (tokens live about two minutes).
$solution = captchano_solve([
    'type'      => 'recaptcha_v2',
    'url'       => $pageUrl,
    'sitekey'   => $m[1],
    'userAgent' => $ua,
    // 'proxy'  => 'http://user:pass@host:port',
], $apiKey);

// 3. Submit the form with the token, same cookies, same user agent.
$response = fetch($pageUrl, $ua, $jar, [
    'username'             => 'demo',
    'password'             => 'demo',
    'g-recaptcha-response' => $solution['token'],
]);

If the site still rejects the token, work through the checklist in the rejected-token guide before you change anything else. Sending a token from a different IP than the solve is the most common cause.

Guzzle and Laravel versions

Guzzle and Laravel's HTTP client send exactly the same JSON, so only the transport changes. In Laravel, do not solve inside a web request. A solve holds a PHP worker for as long as it takes, and PHP's max_execution_time and your FastCGI timeout can cut it off. Put it in a queued job with a timeout longer than the API wait:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Http;

class SolveRecaptcha implements ShouldQueue
{
    use Dispatchable, Queueable;

    public int $timeout = 150;   // longer than the 60 s wait plus polling
    public int $tries   = 2;

    public function __construct(
        private string $url,
        private string $sitekey,
    ) {}

    public function handle(): void
    {
        $response = Http::withToken(config('services.captchano.key'))
            ->timeout(75)
            ->post('https://api.captchano.com/v1/solve?wait=60', [
                'type'    => 'recaptcha_v2',
                'url'     => $this->url,
                'sitekey' => $this->sitekey,
            ]);

        if ($response->failed()) {
            // {"error": {"code": "...", "message": "..."}}
            throw new \RuntimeException($response->json('error.code', 'unknown'));
        }

        if ($response->json('status') !== 'ready') {
            // Still solving after 60 s: poll GET /v1/task/{id} every 5 s.
            $this->release(5);
            return;
        }

        $token = $response->json('solution.token');
        // Use it now: it expires about two minutes after it is issued.
    }
}

With plain Guzzle the call is $client->post('https://api.captchano.com/v1/solve?wait=60', ['headers' => ['Authorization' => 'Bearer ' . $key], 'json' => $task, 'timeout' => 75]). Set http_errors to false if you want to read the error.code body of a 4xx instead of catching an exception.

reCAPTCHA v3 and Enterprise in PHP

For v3, change the task type to recaptcha_v3 and add the action the page passes to grecaptcha.execute, plus a minScore. A token with the wrong action fails the site's check. Our v3 score guide explains how scores work, and the fields are the same as in the helper above.

For Enterprise, the recaptcha_enterprise type covers checkbox and invisible Enterprise widgets only. Score-based Enterprise keys are not supported. Check the script tag first: enterprise.js alone does not tell you which kind you have, as we describe in reCAPTCHA Enterprise explained.

What a wrong token looks like

A bad token does not raise an error on your side; the site just answers as if no captcha was solved. On Google's demo, our placeholder token came back as "Please verify that you are not a robot." Google's own siteverify returns success: false with an error code such as invalid-input-response in that case. If you get this with a real token, log four things before the next attempt: the token's age, the IP and user agent used for the solve, the IP and user agent used for the submit, and the hostname on the page.

Testing your own forms: use Google's test keys

If you own the form, you do not need a solver to test it. Google publishes test keys that always pass: the test secret returned success: true in our run, which lets you check your siteverify code end to end. Our guide to testing reCAPTCHA and Turnstile covers the keys and what each one proves.

When a solver is the wrong tool

Use an official API or an export first if the site offers one. Do not use a solver to get around a site's terms, to create fake accounts, or to scrape data you are not allowed to collect. A solver also does not fix a firewall block such as a Cloudflare 403, an IP ban or a rate limit; it returns a token, not a clean reputation. And if the form needs values computed by JavaScript in the page, a plain PHP POST will not work, so drive a real browser instead, for example with our Playwright reCAPTCHA guide.

How CaptchaNo handles reCAPTCHA from PHP

You send the sitekey and URL and get a token back, solved on our own infrastructure. Failed solves are never billed, you pay only for tasks that return a token, and credit never expires; current rates are on the pricing page. Errors use stable codes such as invalid_sitekey, unsolvable and proxy_unreachable, so you can retry the right ones. Questions from developers go to support@captchano.com and are answered by the people who run the service. We also keep an open-source PHP client on GitHub. As of 2 December 2026 it is not listed on Packagist (the package page returns 404), so the code in this guide uses plain cURL and needs no package.

Frequently Asked Questions

Can PHP solve reCAPTCHA on its own?

No. PHP can request a page, read the sitekey and submit a form, but the challenge itself needs a solving service or a real browser session. In PHP you send the sitekey and URL to a solver API and receive a token. You then place that token in the g-recaptcha-response field when you submit the form.

Do I need Composer or an SDK to solve reCAPTCHA in PHP?

No. The solve request is one HTTPS POST with a JSON body, so PHP's built-in cURL extension is enough. The helper in this guide uses only ext-curl and ext-json. Guzzle and Laravel's HTTP client work too, but they add a dependency without changing what is sent or what comes back.

How long does a reCAPTCHA token last?

Google's documentation says a response token is valid for two minutes and can be verified once. That means you should request the token immediately before you submit the form, not earlier in a long script. A token that is reused, solved too early or sent from a different IP is a common reason a site rejects it.

Why is my PHP script still blocked after I submit the token?

The most common causes are a different IP or user agent between the solve and the submit, a missing cookie from the first page load, a token that is older than two minutes, or a form field the page computes with JavaScript. A firewall block such as a Cloudflare 403 is a separate problem that a token does not fix.

Should I solve captchas inside a Laravel web request?

No. A solve can take many seconds and ties up a PHP worker, and your web server or PHP timeout may cut it off. Dispatch a queued job with a timeout longer than the API wait, then continue the next step from the job. This keeps pages fast and lets the worker retry when a solve fails.

Add reCAPTCHA solving to your PHP scripts

Copy the helper, run it against your own page, and move the solve into a queue job before production. Create a CaptchaNo account to get an API key; the free trial lets you test your own endpoints. The full request reference is linked above.