More languages
How to solve Cloudflare Turnstile in PHP
Turnstile protects many contact, sign up and lookup forms. This guide solves it from plain PHP with no Composer packages at all, using stream contexts and DOM functions that ship with PHP. A token costs $0.84 per 1,000.
Why go without dependencies
Plenty of PHP runs where adding packages is awkward: shared hosting, a legacy app with no Composer setup, a WordPress plugin that should not bundle an HTTP client. PHP's own stream wrappers can send JSON over HTTPS, read response headers and post forms, and the DOM extension parses HTML. Together they cover a complete Turnstile flow. All you need is allow_url_fopen enabled and the OpenSSL extension, which most hosts have. If your project already uses Guzzle or cURL, the same API calls translate directly.
How a Turnstile form works
The page includes a widget, usually a div with class cf-turnstile and a data-sitekey starting with 0x4. When a visitor passes the check, Cloudflare's script writes a token into a hidden input named cf-turnstile-response inside the form. The form posts that field with the others, and the site's server verifies it with Cloudflare. Your PHP code only has to supply the token; the guide on Cloudflare Turnstile explains the widget modes.
Fetch the form and remember the cookies
Stream requests expose response headers in the variable $http_response_header, which PHP fills in the calling scope. The helper below returns the HTML and a cookie string built from the Set-Cookie lines, so the later post belongs to the same session.
<?php
declare(strict_types=1);
function fetch_form(string $url): array
{
$ctx = stream_context_create(['http' => [
'method' => 'GET', 'timeout' => 20, 'ignore_errors' => true,
'header' => "Accept: text/html\r\nAccept-Language: en-US,en;q=0.9\r\n",
]]);
$html = file_get_contents($url, false, $ctx);
$jar = [];
foreach ($http_response_header ?? [] as $line) {
if (stripos($line, 'Set-Cookie:') === 0) {
$pair = trim(explode(';', substr($line, 11), 2)[0]);
[$name] = explode('=', $pair, 2);
$jar[$name] = $pair;
}
}
return [(string) $html, implode('; ', $jar)];
}
Keying the array by cookie name means a cookie that is set twice keeps only its latest value. In PHP 8.4 and newer, http_get_last_response_headers() is the function based replacement for the magic variable; both work at the time of writing.
Read the widget with DOMXPath
Parse the HTML and find the widget, its optional data-action and data-cdata, and every hidden input of the form. Suppressing libxml warnings keeps real world HTML from flooding the log.
function widget_and_fields(string $html): array
{
$dom = new DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$finder = new DOMXPath($dom);
$box = $finder->query('//*[contains(concat(" ", @class, " "), " cf-turnstile ")][@data-sitekey]')->item(0);
if (!$box instanceof DOMElement) {
throw new RuntimeException('no Turnstile widget in the HTML');
}
$hidden = [];
foreach ($finder->query('//form//input[@type="hidden"][@name]') as $node) {
$hidden[$node->getAttribute('name')] = $node->getAttribute('value');
}
unset($hidden['cf-turnstile-response']);
return [
'sitekey' => $box->getAttribute('data-sitekey'),
'action' => $box->getAttribute('data-action') ?: null,
'cdata' => $box->getAttribute('data-cdata') ?: null,
'hidden' => $hidden,
];
}
The concat trick matches the class name as a whole word, so cf-turnstile-wrapper does not count. If the widget is rendered from JavaScript, the key is not in the HTML; the guide on how to find Turnstile parameters shows where to look in the scripts.
Ask the API for a token
function gs_json_call(string $endpoint, array $fields): array
{
$fields['clientKey'] = getenv('GATESOLVER_KEY') ?: 'YOUR_API_KEY';
$ctx = stream_context_create(['http' => [
'method' => 'POST', 'timeout' => 25, 'ignore_errors' => true,
'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
'content' => json_encode($fields, JSON_THROW_ON_ERROR),
]]);
$raw = file_get_contents('https://gatesolver.com/' . $endpoint, false, $ctx);
if ($raw === false) {
throw new RuntimeException("no reply from $endpoint");
}
$out = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
if (($out['errorId'] ?? 0) !== 0) {
throw new RuntimeException("$endpoint: " . ($out['errorCode'] ?? 'unknown'));
}
return $out;
}
function turnstile_token(string $pageUrl, array $w): string
{
$task = ['type' => 'AntiTurnstileTaskProxyLess', 'websiteURL' => $pageUrl, 'websiteKey' => $w['sitekey']];
if ($w['action'] !== null || $w['cdata'] !== null) {
$task['metadata'] = array_filter(['action' => $w['action'], 'cdata' => $w['cdata']]);
}
$id = gs_json_call('createTask', ['task' => $task])['taskId'];
for ($round = 1; $round <= 40; $round++) {
sleep(3);
$st = gs_json_call('getTaskResult', ['taskId' => $id]);
if ($st['status'] === 'ready') {
return $st['solution']['token'];
}
if ($st['status'] === 'failed') {
throw new RuntimeException('Turnstile task failed (no charge)');
}
}
throw new RuntimeException('Turnstile token not ready after two minutes');
}
The ignore_errors option makes PHP return the body even on a non 200 status, so error replies are read as JSON instead of producing a warning and false.
Post cf-turnstile-response with the form
$page = 'https://support.example.com/ticket';
[$html, $cookies] = fetch_form($page);
$w = widget_and_fields($html);
$token = turnstile_token($page, $w);
$fields = $w['hidden'] + [
'name' => 'QA Robot', 'email' => 'qa@example.com',
'message' => 'Weekly form check', 'cf-turnstile-response' => $token,
];
$send = stream_context_create(['http' => [
'method' => 'POST', 'timeout' => 20, 'ignore_errors' => true,
'header' => "Content-Type: application/x-www-form-urlencoded\r\nCookie: $cookies\r\nReferer: $page\r\n",
'content' => http_build_query($fields),
]]);
$result = file_get_contents($page, false, $send);
echo $http_response_header[0] ?? 'no status', PHP_EOL;
Post to the form's action URL, which is often the same page but not always. Look at the form tag or the Network tab to be sure.
Confirming that it worked
The first line of $http_response_header holds the status, such as HTTP/1.1 302 Found for a redirect to a thank you page. Many sites return 200 either way and show an error inside the HTML, so also search $result for a success message you saw when submitting by hand. If the site says the security check failed, the token was probably submitted too late, the cookie was missing, or the form expected a different field name.
Timing and reuse
Tokens are valid once and only for a short time. Solve right before the post, not when the script starts. In a loop over several forms, call turnstile_token once per post. Tokens typically arrive under 3 seconds. Failed tasks, tasks unsolved after 120 seconds, and error replies are not charged.
Cloudflare's other check
If fetch_form returns a "Just a moment" page instead of your form, the site is running the Cloudflare challenge page. That needs a cf_clearance cookie from Cloudflare Challenge, obtained through the same proxy and User-Agent your PHP requests use. Plain PHP streams can send through an HTTP proxy with the proxy and request_fulluri context options.
Running it from cron
A common use is a nightly check that your own contact or support form still works end to end. Wrap the flow in a function that returns true when the confirmation message appears, and have the cron script send you a mail or chat message when it returns false or throws. Write the exception message to the log: createTask: ERROR_ZERO_BALANCE or a missing site key are fixed in minutes once you can see them. Keep the API key in an environment variable set in the crontab or a protected config file, not in the script.
A form check like this costs one Turnstile token per run, a tiny fraction of a cent, and it catches broken mail settings, expired SSL on the form handler and changed field names before a real visitor does.
Plain streams or a client library
Streams are perfect for one or two forms. If your script grows to many pages, retries and parallel requests, a client library gives you connection reuse, middleware and better error objects. The API calls themselves do not change: the same JSON bodies work with cURL, Guzzle or Symfony HttpClient.
Common questions
Does this need cURL or Guzzle?
No. It uses file_get_contents with stream contexts and the DOM extension, which ship with PHP. allow_url_fopen and OpenSSL must be enabled.
Where does $http_response_header come from?
PHP fills it in the local scope after an HTTP stream request. PHP 8.4 adds http_get_last_response_headers as a function alternative.
What if the form has no data-sitekey in the HTML?
The widget is rendered by JavaScript. Read the key from the turnstile.render call in the page scripts.
Is a proxy needed for Turnstile?
No. AntiTurnstileTaskProxyLess needs none. Only the Cloudflare challenge page needs one.
Why send the cookies from the first request?
Many forms pair a hidden CSRF value with a session cookie. Posting without the cookie fails even with a valid token.
Keep reading
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Cloudflare TurnstileThe Turnstile widget from Cloudflare, its managed, non-interactive and invisible modes, and the cf-turnstile-response token field.
- Solve Cloudflare Turnstile in PythonAn asyncio and aiohttp client for Turnstile tasks, with action and cData passed through and the token posted as cf-turnstile-response.