Yandex SmartCaptcha in PHP: Guzzle Form and Time Limit

To handle Yandex SmartCaptcha in PHP without a browser, load the sign-up page with Guzzle, read the sitekey from the data-sitekey attribute, pass it and the page address to yandexSmart() in the CapSkip SDK, and send the returned token back in the smart-token form field. That call is answered by the CapSkip Yandex SmartCaptcha solver, which runs on your own Windows PC. One PHP detail needs care: yandexSmart() waits up to 300 seconds unless told otherwise, and on Windows a web request gets 30 seconds of wall-clock time by default.
What you need
- CapSkip 5.0.0 or later on your Windows machine, the release whose 14 November 2026 changelog lists Yandex SmartCaptcha.
- PHP 8.0 or later plus Composer, with the curl and json extensions enabled. I ran 8.0.30, 8.1.33, 8.2.29, 8.3.28, 8.4.15 and 8.5.0, not 8.0.0 or 8.0.1 (Composer’s platform check on 8.0.30 wanted 8.0.2). A zip download of PHP has no php.ini and no CA bundle, so the first https request from Guzzle fails with cURL error 60: download cacert.pem from curl.se and set curl.cainfo and openssl.cafile in php.ini to its path. On 8.0.30, 8.4.15 and 8.5.0, one https request to capskip.com failed with error 60 without a bundle and returned status 200 with one. The test used the Git for Windows bundle, not cacert.pem.
- capskip 1.8.0 or newer, where yandexSmart() first appears. Composer also chose Guzzle 8.5.2 on all six PHP versions.
- Where CapSkip listens. In Local mode CapSkip listens on 127.0.0.1 and nothing else can reach it. Server mode adds your network or public IP, which the last section before the FAQ covers.
I ran every example against mock servers, one standing in for CapSkip and one for a sign-up site, and sent no real task, so every number below is a mock number. The site rules are mine, apart from the five minute and single check token rules from the Yandex token validation docs. Nothing here shows that a real Yandex protected site accepts a token.
Step 1: install the packages and set up the Guzzle client
# In a PowerShell prompt, in the folder that will hold yandex_signup.php composer require capskip/capskip guzzlehttp/guzzle
Save the PHP blocks of this guide, in order, in one file named yandex_signup.php. The first block creates the CapSkip client and a Guzzle client whose cookie jar carries the session from the page load to the form post. It also fixes one User-Agent string, which CapSkip gets for the solve and the form post reuses unless the CapSkip reply names another.
The CapSkip docs say userAgent is the string presented to Yandex, and that a current Chrome string is used when you send none. A bare Guzzle request announces itself as GuzzleHttp/8 instead. In my mock, a form post with that string was refused on all three tries because the token had been issued for a different User-Agent. That is my mock’s rule, and I can’t show that Yandex checks it. The SDK copies a userAgent from the reply into its result when the server sends one, and Step 3 passes it on. The Yandex section of the API docs does not say CapSkip sends one for this method, so that branch ran only against my mock.
<?php
// yandex_signup.php: run it with php yandex_signup.php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use CapSkip\CapSkip;
use CapSkip\Exceptions\ApiException;
use CapSkip\Exceptions\CapSkipError;
use CapSkip\Exceptions\TimeoutException;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
const SIGNUP_URL = 'https://example.com/signup'; // the page that shows the widget
const WAIT = 60; // seconds the SDK may wait for one token
// Use a current Chrome string. CapSkip is told this one, and so is the site.
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
. '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
// Local mode. In Server mode, use your server's address as the host.
$solver = new CapSkip(['host' => '127.0.0.1', 'port' => 8080]);
// One client keeps the cookie jar between the page load and the form post.
// Guzzle sends no Referer of its own, so the form post adds it below.
$http = new Client([
'cookies' => new CookieJar(),
'headers' => ['User-Agent' => USER_AGENT],
'timeout' => 20,
'http_errors' => false,
]);Step 2: read the Yandex SmartCaptcha sitekey from the page
The widget sits in a container with the class smart-captcha, and its sitekey is the data-sitekey attribute of that container. Pages that draw the widget from their own script pass the same key to smartCaptcha.render as sitekey. The function below tries the container first and the render call second.
It checks each start tag and wants the class on the same tag as the attribute, because a page can carry other data-sitekey attributes. My mock page had a reCAPTCHA div before the widget and a div with the class smart-captcha-note beside it; the function skipped both. It also read single quotes, a class after the attribute and the render form. The SDK refused a placeholder key and the function raised its own RuntimeException on a page with no widget, both before any task.
function read_sitekey(string $html): string
{
// The container is the start tag whose class list has smart-captcha. A page
// can hold other data-sitekey attributes (reCAPTCHA has one), so match both.
preg_match_all('/<[a-z][^>]*>/i', $html, $tags);
foreach ($tags[0] as $tag) {
$isWidget = preg_match('/class\s*=\s*(["\'])(?:(?!\1).)*(?<![\w-])smart-captcha(?![\w-])/is', $tag);
if ($isWidget && preg_match('/data-sitekey\s*=\s*(["\'])(.*?)\1/is', $tag, $m)) {
return $m[2];
}
}
// A page that renders the widget from its own script passes the key to
// smartCaptcha.render in an options object.
if (preg_match('/smartCaptcha\.render\s*\([^{]*\{[^}]*?\bsitekey\s*:\s*(["\'])(.*?)\1/is', $html, $m)) {
return $m[2];
}
throw new RuntimeException('no SmartCaptcha sitekey in the page');
}Client keys usually start with ysc1_, but the SDK accepts any 16 to 120 letters, digits, underscores and hyphens, so the older style key from the SDK example passed my mock. If the page builds the widget with JavaScript after load, the sitekey is not in the HTML Guzzle fetches: read it once from the page scripts in your browser tools and put it in the code.
Step 3: fetch the token without outrunning PHP’s time limit
Call yandexSmart(sitekey, url, options): it submits the task, polls for you and hands back an array. Pass the page’s real address as url, since Yandex tests the sitekey against the domain it runs on. In options, userAgent is the string from Step 1 and timeout is how many seconds the SDK may wait.
Yandex tasks run in a real browser, so the SDK source gives them recaptchaTimeout, which is 300 seconds, and not defaultTimeout. With defaultTimeout set to 5 and a token that took 14 seconds, the token still arrived, while recaptchaTimeout set to 10 made the call fail after 12.8 seconds.
function get_token(CapSkip $solver, string $sitekey): array
{
// On Windows a web request ends at max_execution_time of wall-clock time, and
// the SDK can sleep up to 5 seconds past its own timeout. Lift the limit for
// this request: the wait, that last sleep and 25 seconds for the rest.
set_time_limit(WAIT + 30);
$result = $solver->yandexSmart($sitekey, SIGNUP_URL, [
'userAgent' => USER_AGENT,
'timeout' => WAIT,
]);
// The reply can name the User-Agent the token was earned with. If it does,
// the form post must use that one, so hand both back.
return [$result['token'], $result['userAgent'] ?? USER_AGENT];
}The SDK does not watch the clock continuously. It reads the result at 0, 0.25, 0.75, 1.75, 3.75 and 7.75 seconds, then every 5 seconds, and tests its deadline only when the next read is due. With a timeout of 20 and a task that never finished, the mock saw reads at 0.0, 0.26, 0.77, 1.79, 3.80, 7.83, 12.84 and 17.85 seconds, and the TimeoutException came at 22.86. With a timeout of 15 and a token ready after 13 seconds, the read at 12.82 came too early, and the call gave up at 17.83 without collecting the token. A timeout should end after the read you expect to succeed. The CapSkip Yandex page says a job typically takes 15 to 30 seconds (a vendor claim I could not measure), so the script waits 60.
Two clocks now run. On Windows, PHP’s max_execution_time counts wall-clock time: it read 0 on the command line even with 30 in php.ini, and it was 30 under the built-in web server. The table shows what happens in a web request (PHP 8.4.15, Windows, mock CapSkip, php -S with max_execution_time 30).
| Setup | Result |
|---|---|
| This script, a task that never finishes | The out of time message after 62.96 seconds, from a timeout of 60 |
| This script, token ready after 40 seconds | Signed up after 42.94 seconds |
| The set_time_limit line removed, token ready after 40 seconds | Fatal error, Maximum execution time of 30 seconds exceeded, after 32.93 seconds |
| The set_time_limit line and the timeout option removed, a task that never finishes | The same fatal error after 32.89 seconds, a long way short of the 300 second default |
The PHP manual says that off Windows the limit counts CPU time only, so on Linux a script that mostly sleeps rarely trips max_execution_time, and the web server’s own timeout is the limit to check there. I tested none of that. On Windows, a fatal error is not an exception, so no catch block sees it. The set_time_limit call restarts PHP’s counter, so the script gives the request the wait, the 5 seconds the SDK can overshoot and 25 more for the form post. Details on the call are in the PHP manual page for set_time_limit. PHP 8.0.30 gave 63.12, 43.08, 33.02 and 33.03 seconds in the same rows.
Step 4: post the token as smart-token
The widget writes its token into a hidden input named smart-token with JavaScript, so the HTML Guzzle fetched has no such input. The function below collects every hidden input of the page, with single or double quotes and entities decoded, and adds smart-token itself. My mock refused the form when the hidden inputs were left out (the csrf value was missing) and when entity values were sent undecoded. On PHP 8.0.30 the default flags of html_entity_decode leave an apostrophe written as a numeric entity alone, so the code passes ENT_QUOTES and ENT_HTML5. Guzzle sends no Referer unless told, and my mock refused a form without one, so the post names the sign-up page. It also sends the User-Agent that get_token returned: when my mock’s reply named a different string, a post with the constant USER_AGENT failed three times and the returned string passed.
The Yandex docs give a token five minutes and one check. The site makes that check on its own server with its secret server key, so your script never validates anything. In the mock, the same token posted twice was refused the second time, and one held for 4 seconds was refused when I set the mock’s lifetime to 3.
function submit_form(Client $http, string $html, string $token, string $agent, string $email): string
{
// Reads one attribute of a tag, in single or double quotes, with entities decoded.
$attr = static function (string $tag, string $name): ?string {
if (preg_match('/(?<![\w-])' . $name . '\s*=\s*(["\'])(.*?)\1/is', $tag, $m) !== 1) {
return null;
}
return html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5);
};
$fields = ['email' => $email];
// Every hidden input of the page goes along, as a browser would send it.
preg_match_all('/<input\b[^>]*>/i', $html, $inputs);
foreach ($inputs[0] as $input) {
$name = $attr($input, 'name');
if (strtolower((string) $attr($input, 'type')) === 'hidden' && $name !== null) {
$fields[$name] = $attr($input, 'value') ?? '';
}
}
// The widget adds this one with JavaScript, so the HTML may not have it.
$fields['smart-token'] = $token;
$reply = $http->post(SIGNUP_URL, [
'form_params' => $fields,
'headers' => ['Referer' => SIGNUP_URL, 'User-Agent' => $agent],
]);
return (string) $reply->getBody();
}Step 5: assemble the complete Yandex SmartCaptcha in PHP script
The final block completes the file. Set SIGNUP_URL, the field name email in submit_form and your own success and refusal texts. Test for a phrase that only a captcha refusal contains, because a re-shown form still holds the widget markup.
A retry pays off in two cases: the site refused the token (that token is spent, so ask for a new one), and CapSkip answered ERROR_CAPTCHA_UNSOLVABLE. The CapSkip docs say a sitekey Yandex rejects, a domain the key is not registered for and an unreachable proxy would fail again, so those end the script. Each try loads a fresh page, which gives a new cookie and a new csrf value.
function sign_up(CapSkip $solver, Client $http, string $email): string
{
for ($try = 1; $try <= 3; $try++) {
$page = (string) $http->get(SIGNUP_URL)->getBody(); // fresh cookies and csrf value
try {
[$token, $agent] = get_token($solver, read_sitekey($page));
} catch (ApiException $e) {
if (!str_contains($e->getMessage(), 'ERROR_CAPTCHA_UNSOLVABLE')) {
throw $e; // a refused sitekey or domain would fail the same way again
}
error_log("try $try: ERROR_CAPTCHA_UNSOLVABLE, new task");
continue;
}
$reply = submit_form($http, $page, $token, $agent, $email);
if (str_contains($reply, 'signed up')) { // a sign your site shows on success
return $reply;
}
if (!str_contains($reply, 'Captcha check failed')) { // your site's own refusal text
throw new RuntimeException('refused, but not for the captcha');
}
error_log("try $try: token refused, new page and token");
}
throw new RuntimeException('no sign-up after 3 tries');
}
try {
echo sign_up($solver, $http, '[email protected]'), "\n";
} catch (TimeoutException $e) {
echo 'out of time: ', $e->getMessage(), "\n";
exit(2);
} catch (CapSkipError | GuzzleException | RuntimeException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
exit(1);
}# From the same PowerShell prompt, in the folder that holds the file php yandex_signup.php
Against my mock, each row below gave the same result on all six PHP versions, except where a row says otherwise. PHP 8.5.0 also prints extra Deprecated notices (see the errors below).
| Mock setting | Result |
|---|---|
| Widget container with the sitekey in data-sitekey | One task, form accepted |
| Single quotes, with the class after the attribute | One task, form accepted |
| No container, the key passed to smartCaptcha.render | One task, form accepted |
| A reCAPTCHA div and a smart-captcha-note div around the widget | One task with the Yandex key, form accepted |
| The page shows the placeholder YOUR_SITE_KEY | ValidationException, no task |
| No widget in the served HTML | RuntimeException, no task |
| The site refuses the first token with its refusal text | A second task, then the form was accepted |
| The first two tasks fail with ERROR_CAPTCHA_UNSOLVABLE | Two retry lines, then the third task passed |
| All three tasks unsolvable | Three tasks, RuntimeException, no form sent |
| The poll returns a sitekey, domain or proxy error | ApiException after one task, no form, no retry |
| Key validation on, without and then with apiKey | ERROR_KEY_DOES_NOT_EXIST, then form accepted |
| Form post left with Guzzle’s own User-Agent | Three tasks, three refusals, RuntimeException |
| The userAgent option left out | Form accepted, because my mock only compares a string the task named |
| Form post without a Referer header | One task, refused, RuntimeException |
| Hidden inputs of the page not sent | One task, refused, RuntimeException |
| Hidden input values sent without decoding | One task, refused, RuntimeException |
| A reply that names another User-Agent, and the post uses it | One task, form accepted |
| The same reply, and the post uses the constant USER_AGENT | Three tasks, three refusals, RuntimeException |
| html_entity_decode called with its default flags | Refused on 8.0.30, accepted on 8.4.15 and 8.5.0 (8.1 to 8.3 not run for this row) |
| No cookie jar in the Guzzle client | Three tasks, three refusals, RuntimeException |
| CapSkip port closed | NetworkException after 2.1 to 2.3 seconds |
| The site answers after 25 seconds | GuzzleHttp NetworkTimeoutException after 20.1 seconds |
No real site took part in any row. Each CapSkip request, the submit and every poll, caused one curl_close notice on 8.5.0: two for a task whose token was ready at once, six for one that needed five polls.
Common errors
A row marked seen is one I triggered against the mock; the other rows are taken from the Yandex SmartCaptcha API docs.
| Error | Cause | Fix |
|---|---|---|
| ValidationException | An argument failed the SDK checks, so nothing was sent (seen). It covered a short, spaced, empty or 121 character sitekey, a relative or ftp page address, the options action and invisible, and a proxy type of SOCKS4 | Read the message and correct that argument |
| ERROR_RECAPTCHA_INVALID_SITEKEY | Yandex does not accept the sitekey (docs) | Copy it again from the page. The script stops, because a resubmission would fail |
| ERROR_RECAPTCHA_INVALID_DOMAIN | The sitekey is not allowed on the domain of your page address (docs) | Send the address of the page that holds the widget |
| ERROR_PROXY_CONNECT_REFUSED | The solve could not reach Yandex through your proxy (docs) | Check the proxy in the options or in CapSkip |
| ERROR_CAPTCHA_UNSOLVABLE | The challenge was not passed (docs) | Send another task; the script does so up to three times |
| ERROR_WRONG_USER_KEY or ERROR_KEY_DOES_NOT_EXIST | API Key Validation is on and your key is absent or wrong. A call without apiKey goes out with the key capskip, and my mock answered the second code (seen) | Pass your key as apiKey in the constructor array |
| TimeoutException | No token before the deadline (seen) | Raise the timeout, and check the CapSkip monitor |
| NetworkException | Nothing answered at that host and port (seen, after about 2 seconds) | Start CapSkip and compare its connection settings with the constructor array |
| Fatal error: Maximum execution time | On Windows, the wait outlasted PHP’s wall-clock limit (seen) | Keep the set_time_limit call, or a timeout under the limit |
| Deprecated: Function curl_close() | PHP 8.5 deprecates the function and the SDK still calls it after every request to CapSkip (seen, one notice per request) | The solve works. Lower error_reporting or turn off display_errors until the SDK drops the call |
| GuzzleHttp NetworkTimeoutException | The site did not answer within the client’s 20 seconds (seen, with a mock site that waited 25) | Raise the timeout in the Guzzle client or check the site |
| The site refuses a token you expected to work | The token was used before, was too old, or came with another User-Agent (mock rules) | One token per form, posted at once, with the same string |
Calling CapSkip from a second machine
With Server mode on, CapSkip also listens on your network or public IP, so the PHP script may run elsewhere: give the constructor array the address of the CapSkip machine as host, and its port if you changed it. Server mode needs CapSkip to run as administrator, and the Server switch lives in the connection settings of the setup guide. That mode leaves the CapSkip port open to every address, so set the Windows Firewall to block it by default, allow only the machines that need it, and turn on API Key Validation as a second lock.
FAQ
Do I need Guzzle to solve Yandex SmartCaptcha in PHP?
No. yandexSmart() only returns a token, and any HTTP client can send it in the smart-token field. Guzzle saves you the cookie handling.
Should the form post use the same proxy as the solve?
The CapSkip Yandex page advises it, since a site can send the visitor’s address to Yandex when it checks a token. The SDK takes a proxy option as a string or as an array with type and uri, and Guzzle has its own proxy request option. My mock saw the proxy arrive; I ran no real one. Settings for the solve are covered in the CapSkip proxy guide.
How long does a SmartCaptcha token last?
Five minutes and one check, per the Yandex docs, so request it just before the form post.
Four habits cover Yandex SmartCaptcha in PHP: read the key from the widget’s own tag, keep one User-Agent on both calls, give the SDK a timeout that fits PHP’s limit, and ask for a fresh token whenever a form is refused. CapSkip is an unlimited captcha solver that runs on your own PC, so a refused token costs nothing but another trip round the loop. For more CAPTCHA types from PHP, visit the PHP CAPTCHA solver page.
