PHP

PHP examples

Six examples ready to copy, from the first call to error handling, with the hosted sample certificate (fictitious data).

Before you start

Three steps, once.

  1. Create an API key

    In the panel, under API Keys.

  2. Put the key in the environment

    In the DOCSOCR_API_KEY variable, which the examples read. The prices example needs no key.

  3. Save and run

    Save each example under the name shown above its code. Its first lines say what it needs to run.

Your first call

Sends the hosted sample certificate (fictitious data) and prints the JSON answer.

first-call.php
<?php
// Your first call: extract the hosted sample certificate (fictitious data).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;

A local file in base64

Reads an image from your machine and sends it in base64, with no public URL needed.

local-file.php
<?php
// Extract a certificate from a local file, sent in base64.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$imageBase64 = base64_encode(file_get_contents('certificate.jpg'));

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'base64',
        'imageBase64' => $imageBase64,
        'requestId' => bin2hex(random_bytes(16)), // one id per document
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;

An image outside our standard

With resizeImage: true, an image outside our size standard is resized on our side for 1 credit more, instead of refused.

resize.php
<?php
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
        'resizeImage' => true,
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;
echo 'resized: ', var_export($answer['imageResized'] ?? false, true), ' credits: ', $answer['creditsCharged'], PHP_EOL;

The fast engine

Asks for the fast engine: it is tried first, at its own price, and the standard engines answer when it cannot. The answer names the engine that answered and what it cost.

fast.php
<?php
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
        'engine' => 'fast',
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo 'engine: ', $answer['engine'], ' credits: ', $answer['creditsCharged'], PHP_EOL;

Errors and retries

Handles every answer and retries with the same requestId: for 15 minutes, a repeat of a finished request gets the same answer at no charge, and a repeat of one still running gets a 409, to wait.

errors.php
<?php
// Extract a certificate, handling every answer, with retries that never charge twice.
// Each retry sends the same requestId: a repeat of a finished request gets its
// kept answer at no charge, and a repeat of one still running is told to wait (409).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

const ENDPOINT = 'https://api.docsocr.com/api/v1/documents/birth-certificate';
// No engine could answer: nothing was charged, and a retry may succeed
const RETRY_LATER = ['EXTRACTION_BUSY', 'EXTRACTION_TIMEOUT', 'EXTRACTION_UNAVAILABLE'];
// Still in progress, too many requests, the service restarting
const RETRY_STATUS = [409, 429, 502, 503, 504];

function extractCertificate(string $imageUrl, int $attempts = 5): array
{
    $requestId = bin2hex(random_bytes(16)); // one id per document, the same on every retry
    for ($attempt = 0; $attempt < $attempts; $attempt++) {
        $backoff = 2 ** $attempt; // seconds: 1, 2, 4, 8
        $request = curl_init(ENDPOINT);
        curl_setopt_array($request, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode(['imageType' => 'url', 'imageUrl' => $imageUrl, 'requestId' => $requestId]),
        ]);
        $body = curl_exec($request);
        if ($body === false) { // a timeout or a dropped connection
            sleep($backoff);
            continue;
        }
        $status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
        $answer = json_decode($body, true) ?? [];
        if ($status === 201 && !empty($answer['success'])) {
            return $answer;
        }
        // Wait as long as the answer asks (retryAfter); a limit that resets
        // later, such as a daily quota, is not worth waiting for
        $wait = (int) ($answer['retryAfter'] ?? $backoff);
        $retry = in_array($answer['errorCode'] ?? '', RETRY_LATER, true) || in_array($status, RETRY_STATUS, true);
        if ($retry && $wait <= 60) {
            sleep($wait);
            continue;
        }
        // 400 the body, 401 the key, 402 NOT_ENOUGH_CREDITS, 422 the image
        // (its errorCode says what to fix), DOCUMENT_NOT_RECOGNIZED: fix it, don't retry
        $message = implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? ''));
        throw new RuntimeException("$status " . ($answer['errorCode'] ?? '') . " $message");
    }
    throw new RuntimeException('No answer after retries: try again later');
}

try {
    $answer = extractCertificate('https://docsocr.com/samples/certidao-nascimento-exemplo.jpg');
    echo $answer['data']['dados_pessoais']['nome_completo'], ' credits: ', $answer['creditsCharged'], PHP_EOL;
} catch (RuntimeException $error) {
    fwrite(STDERR, $error->getMessage() . PHP_EOL);
    exit(1);
}

Prices

Reads the price of an extraction in credits, per engine and for resizeImage. No key needed.

prices.php
<?php
// The price of an extraction, in credits, per engine and for resizeImage.
// A public endpoint: no key needed. Needs the curl extension.

$request = curl_init('https://api.docsocr.com/api/v1/documents/prices');
curl_setopt_array($request, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
$body = curl_exec($request);
if ($body === false || curl_getinfo($request, CURLINFO_RESPONSE_CODE) !== 200) {
    fwrite(STDERR, 'The price list did not answer' . PHP_EOL);
    exit(1);
}
foreach (json_decode($body, true) as $name => $credits) {
    echo "$name: $credits credit(s)", PHP_EOL;
}

Ready to start?

Create your account, get free credits and run the first example with your key.