reCAPTCHA
How to solve reCAPTCHA v2 in PHP
PHP can drive the whole reCAPTCHA v2 flow on its own: create a task, wait for the token and post the form. This guide shows a cURL client first and a Guzzle version for projects that already use Composer.
Where PHP fits in this job
PHP is often the language of the back office tool that has to talk to another site: a monitoring cron job, a WordPress plugin that checks a partner form, a Laravel command that collects public listings. In those jobs there is rarely a browser around, so the goal is to get a valid g-recaptcha-response value from the API and send it in the same HTTP request a browser would make.
Everything below targets PHP 8.1 or newer with the cURL extension enabled, which is the default on almost every host. You will need your API key and the site key of the widget, which sits in the page's data-sitekey attribute.
A dependency free cURL client
The first version uses nothing but the cURL extension. One function performs the JSON request and raises on API errors; the other creates the task and polls it. JSON errors throw too, thanks to JSON_THROW_ON_ERROR, so a malformed reply never turns into a silent null.
<?php
declare(strict_types=1);
const GS_ENDPOINT = 'https://gatesolver.com';
function gs_request(string $method, array $fields): array
{
$fields['clientKey'] = getenv('GATE_KEY') ?: 'YOUR_API_KEY';
$ch = curl_init(GS_ENDPOINT . '/' . $method);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($fields, JSON_THROW_ON_ERROR),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException('Transport error: ' . curl_error($ch));
}
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if (!empty($data['errorId'])) {
throw new RuntimeException(trim($data['errorCode'] . ' ' . ($data['errorDescription'] ?? '')));
}
return $data;
}
The solve function sits in the same file and builds on gs_request():
function gs_recaptcha_v2(string $pageUrl, string $siteKey): string
{
$job = gs_request('createTask', ['task' => [
'type' => 'ReCaptchaV2TaskProxyLess', // no proxy on our side
'websiteURL' => $pageUrl,
'websiteKey' => $siteKey,
]]);
$stopAt = time() + 125;
do {
sleep(3);
$res = gs_request('getTaskResult', ['taskId' => $job['taskId']]);
if ($res['status'] === 'ready') {
return $res['solution']['gRecaptchaResponse'];
}
if ($res['status'] === 'failed') {
throw new RuntimeException('Task failed and was not charged');
}
} while (time() < $stopAt);
throw new RuntimeException('Timed out waiting for the token');
}
There is no curl_close() call: since PHP 8 the handle is an object that is freed when it goes out of scope, and the function is deprecated in recent releases. The loop stops a few seconds after 120 seconds, the point at which an unsolved task is closed as failed and costs nothing.
The same client with Guzzle
If your project already pulls in guzzlehttp/guzzle, the json request option handles encoding and headers for you. Keep one client instance for the life of the script so the connection is reused between polls.
use GuzzleHttp\Client;
$gate = new Client(['base_uri' => 'https://gatesolver.com/', 'timeout' => 30]);
$key = $_ENV['GATE_KEY'] ?? 'YOUR_API_KEY';
$ask = function (string $path, array $body) use ($gate, $key): array {
$reply = $gate->post($path, ['json' => ['clientKey' => $key] + $body]);
$out = json_decode((string) $reply->getBody(), true, 512, JSON_THROW_ON_ERROR);
if (($out['errorId'] ?? 0) !== 0) {
throw new DomainException($out['errorCode']);
}
return $out;
};
$taskId = $ask('createTask', ['task' => [
'type' => 'ReCaptchaV2TaskProxyLess', 'websiteURL' => 'https://partners.example.net/apply',
'websiteKey' => '6Lc_PARTNER_FORM_KEY',
]])['taskId'];
The polling part is the same loop as before, calling $ask('getTaskResult', ['taskId' => $taskId]). Because the closure throws DomainException for API errors and Guzzle throws its own TransferException family for network problems, you can catch the two separately and decide which ones deserve another attempt.
Post the token with the form
A form protected by reCAPTCHA v2 expects the token in a field named g-recaptcha-response, next to its usual fields. Load the form page first with a cookie file so the session and any CSRF value are set, read the hidden inputs, then submit everything together.
$jar = sys_get_temp_dir() . '/form-session.txt';
$page = 'https://partners.example.net/apply';
$fetch = curl_init($page);
curl_setopt_array($fetch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar]);
$html = (string) curl_exec($fetch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xp = new DOMXPath($dom);
$csrf = $xp->evaluate('string(//input[@name="_token"]/@value)');
$siteKey = $xp->evaluate('string(//*[@data-sitekey]/@data-sitekey)');
$submit = curl_init($page);
curl_setopt_array($submit, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $jar,
CURLOPT_POSTFIELDS => http_build_query([
'_token' => $csrf,
'company' => 'Test Co',
'g-recaptcha-response' => gs_recaptcha_v2($page, $siteKey),
]),
]);
$result = curl_exec($submit);
echo $result === false ? curl_error($submit) : 'HTTP ' . curl_getinfo($submit, CURLINFO_RESPONSE_CODE);
Field names such as _token and company are placeholders: open the form in your browser's developer tools, submit it once by hand, and copy the exact names from the request. The XPath expressions above read the CSRF value and the site key from the same HTML, so the two always belong to the same page load.
Choosing which errors to retry
Two codes are temporary and free: ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE. Wrap gs_recaptcha_v2() in a loop that retries those up to two times. Treat ERROR_ZERO_BALANCE as a signal to alert someone, and treat ERROR_KEY_DENIED_ACCESS as a broken deployment: if you rotated the key in your account, the old one stopped working at that moment, because each account has exactly one active key.
When you run the solver from a cron job, also guard against overlapping runs with flock() on a lock file. Two copies of the same job solving the same form at once double your spend for no gain.
Running the solver from a queue worker
A web request is the wrong place to wait for a CAPTCHA. PHP-FPM workers are a limited pool, and a request that sleeps for twenty seconds holds one of them the whole time. Move the solve and the form submit into a background job instead: a Laravel queue job, a Symfony Messenger handler, or a plain CLI script started by cron or systemd. The web side only records what needs to be done and returns at once.
Queue workers also give you retries for free. Configure the job with a small number of attempts and a backoff of a few seconds, and let the exception from gs_request() bubble up for the temporary codes. For permanent codes, catch the exception, mark the job as failed and notify someone, so the queue does not keep spending attempts on a missing key or an empty balance.
Keep the API key in the environment of the worker process (GATE_KEY in the examples) rather than in a config file under version control. When you rotate the key in your account, the old value stops working immediately, so restart the workers right after you update the variable.
Upgrading an older in.php script
Plenty of PHP tools written years ago speak the in.php and res.php format: a GET to in.php with method=userrecaptcha, googlekey and pageurl, then repeated calls to res.php?action=get until the reply stops saying CAPCHA_NOT_READY. GateSolver answers that format too, so the quickest upgrade is to change the host in the script and keep everything else. Add json=1 if you would rather parse JSON than split OK| strings. When you have time to refactor, the createTask client above is easier to extend to other task types; the in.php migration guide walks through both routes.
When the token is refused
The form answering with "please complete the CAPTCHA" usually means the token arrived late, was reused, or belonged to another page. Tokens are valid for about two minutes and only once, so solve right before the submit, never at the start of a long script. If you still see refusals, the site may tie the token to the visitor IP; switch to ReCaptchaV2Task with a proxy field set to the same proxy you pass to cURL with CURLOPT_PROXY.
The reCAPTCHA v2 task page lists every accepted field, and the API docs show the in.php compatible endpoint if you are updating an older PHP script that already speaks that format.
Common questions
Which PHP version do these examples need?
PHP 8.1 or newer with the cURL extension. The Guzzle variant also needs guzzlehttp/guzzle installed through Composer.
Can an old in.php style PHP script use GateSolver?
Yes. Point it at https://gatesolver.com/in.php and res.php; the userrecaptcha method is supported for reCAPTCHA v2.
Why does my cron job spend more than expected?
Overlapping runs solve the same form twice. Use a lock file with flock so only one copy runs at a time.
Does sleep() block my whole PHP application?
It blocks only the current process. Run solving in a CLI worker or queue job instead of inside a web request.
Where do I find the field names to post?
Submit the form once by hand with developer tools open and copy the names from the request in the network tab.
Keep reading
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- Site keyThe public value a widget loads with, where it hides in HTML or scripts, and why token tasks require it.
- Moving an in.php client to GateSolverPoint an existing in.php and res.php client at GateSolver: change the base URL, check its methods, switch on json=1.
- API docscreateTask, getTaskResult, getBalance, error codes and the in.php format.