NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

More languages

How to solve image text CAPTCHAs in PHP

Distorted text pictures still guard many older PHP era forms. This guide downloads the picture in the right session, encodes it with base64_encode, reads it with an ImageToTextTask at $0.28 per 1,000, and submits the answer.

How an image CAPTCHA ties to a session

When a form page loads, the server picks a random string, stores it in your session and renders a picture of it at a URL such as /captcha.php. When the form is submitted, the server compares the typed text with the stored string. Everything depends on the session cookie: the picture you download must belong to the same session that submits the form. Most failed attempts with image CAPTCHAs come from losing that link, not from wrong recognition. The image CAPTCHA entry covers the variants.

Set up Symfony HttpClient with cookies

This guide uses symfony/http-client, a standalone component that works in any PHP project, plus symfony/browser-kit for cookie handling and symfony/css-selector so the crawler accepts CSS selectors. Install all three with Composer. HttpBrowser wraps the HTTP client with a cookie jar and history, so every request carries the session automatically.

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

use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\HttpClient\HttpClient;

$portal = new HttpBrowser(HttpClient::create(['timeout' => 20]));
$crawler = $portal->request('GET', 'https://registry.example.gov/search');

$img = $crawler->filter('img#captcha_img, img[src*="captcha"]')->first();
$imgUrl = $img->image()->getUri();   // absolute URL, resolved against the page

$portal->request('GET', $imgUrl);
$bytes = $portal->getInternalResponse()->getContent();
$picture = base64_encode($bytes);

image()->getUri() resolves relative paths for you. Downloading the picture through the same HttpBrowser sends the session cookie, so the image and the later submit share a session. base64_encode produces plain base64 without the data:image/png;base64, prefix, which is exactly what the task expects.

A reader for ImageToTextTask

For the API calls, a plain Symfony HttpClient instance is enough. Its toArray() method decodes JSON and throws on transport errors. Image tasks finish quickly, so the loop checks every second.

use Symfony\Contracts\HttpClient\HttpClientInterface;

final class CaptchaTextReader
{
    public function __construct(private HttpClientInterface $http, private string $apiKey) {}

    private function ask(string $route, array $fields): array
    {
        $data = $this->http->request('POST', "https://gatesolver.com/$route", [
            'json' => ['clientKey' => $this->apiKey] + $fields,
        ])->toArray(false);
        if (($data['errorId'] ?? 0) !== 0) {
            throw new RuntimeException($route . ' failed: ' . ($data['errorCode'] ?? '?'));
        }
        return $data;
    }

    public function read(string $base64, ?string $module = null): string
    {
        $task = ['type' => 'ImageToTextTask', 'body' => $base64];
        if ($module !== null) {
            $task['module'] = $module;
        }
        $taskId = $this->ask('createTask', ['task' => $task])['taskId'];
        for ($i = 0; $i < 60; $i++) {
            usleep(1_000_000);
            $res = $this->ask('getTaskResult', ['taskId' => $taskId]);
            if (($res['status'] ?? '') === 'ready') {
                return $res['solution']['text'];
            }
            if (($res['status'] ?? '') === 'failed') {
                throw new RuntimeException('image could not be read (no charge)');
            }
        }
        throw new RuntimeException('no text after a minute');
    }
}

Passing false to toArray() stops Symfony from throwing on non 2xx statuses, so API error replies are still read as JSON and turned into a clear exception.

Submit the answer with the form

With HttpBrowser, submitting a form is a matter of selecting the button and passing values. Hidden fields in the form are included automatically.

$reader = new CaptchaTextReader(HttpClient::create(['timeout' => 25]), getenv('GATESOLVER_KEY') ?: 'YOUR_API_KEY');
$text = $reader->read($picture);

$form = $crawler->selectButton('Search')->form([
    'company_number' => '09876543',
    'captcha_code' => $text,
]);
$result = $portal->submit($form);
$found = $result->filter('.result-row')->count();
echo $found > 0 ? "found $found rows" : 'no rows; check the captcha message', PHP_EOL;

Replace the button label and the field names with those of your form. Note that $crawler is the page from the first request; it still holds the form and its hidden fields even though the browser has since loaded the picture.

Without Symfony: cURL and in.php

If adding components is not an option, the core pieces are the same in plain PHP: a cURL handle with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR pointing at one file for all three requests, base64_encode on the downloaded bytes, and the JSON task. Older scripts written for the in.php format can keep their shape: post method=base64, body, key and json=1 to https://gatesolver.com/in.php, then read res.php?action=get until the text arrives. The in.php migration guide covers that route.

Case, spaces and confusable characters

Many text CAPTCHAs are case sensitive. Submit the text exactly as returned. Do not apply strtolower or trim unless you know the site ignores case or padding. If a site consistently uses only digits or only capitals, you may normalise afterwards, for example by replacing a lowercase o with 0 in a digits only field. The FAQ on case sensitivity covers this.

Improving accuracy

  • Send the original bytes. Resizing or recompressing the picture loses detail the recognizer uses.
  • Try a module. The optional module field selects a recognition model for a particular text style. Leave it out at first and try it if answers are often wrong.
  • Set a score threshold. The optional score field (0.8 to 1) asks for answers above a confidence level. Lower confidence results then fail for free instead of returning a weak guess.
  • Retry once on a wrong answer. Reload the form, which issues a new picture, and solve again. Do not submit the same picture twice.

Cost and errors

Image tasks are among the cheapest, at $0.28 per 1,000, and usually finish under 1 seconds. Unreadable pictures return ERROR_CAPTCHA_UNSOLVABLE and cost nothing. Stop on ERROR_ZERO_BALANCE and ERROR_KEY_DENIED_ACCESS rather than retrying. The Image to Text page lists all task fields.

Good uses include automating your own lookups on public registries and legacy portals that permit automated queries, and accessibility tools.

Checking the picture before you send it

A quick sanity check saves wasted tasks. Look at the response's content type (getInternalResponse()->getHeader('Content-Type')) and the byte count: an HTML error page or a tiny response means the URL or session is wrong, and no recognizer can read it. While developing, write the bytes to a file with file_put_contents and open it, so you see exactly what the API will see.

Some forms generate the picture with a random query string each time, such as captcha.php?r=0.83. That is fine as long as you use the URL from the page you loaded, not a URL cached from an earlier run.

Scheduling regular lookups

For a daily batch, loop over your inputs and create a new HttpBrowser for each lookup, so each one has its own session, picture and answer. Add a pause of a second or two between lookups; registries that still use text CAPTCHAs are often small systems, and a gentle pace keeps your automation welcome. Write results and the task id for each lookup to a log, which makes any refused answer easy to trace back to the picture that produced it.

Common questions

Why must the picture be downloaded with the same cookie?

The server stores the expected text in your session. A picture fetched without the cookie belongs to a different session and never matches.

Does base64_encode add a data URL prefix?

No. It returns plain base64, which is the format ImageToTextTask expects in its body field.

Do I need Symfony components for this?

No. They make cookies and forms convenient, but cURL with a cookie file and json_encode work the same way.

How often should I poll for image tasks?

Every second. Text recognition finishes much faster than token tasks.

What happens with an unreadable picture?

The task returns ERROR_CAPTCHA_UNSOLVABLE and is not charged. Reload the form for a new picture and try again.

Keep reading