Skip to main content

Confirm

Are you sure?

PHP · Code recipe

Take a screenshot of a website in PHP

Save a full-page PNG of any website, in PHP 8.1+ with the curl extension. Every program on this page runs as it stands — each one was run against a stub of the API before it was published.

By · Last updated: September 2026

TL;DR

To take a screenshot of a website in PHP, POST its URL to https://urlpipe.dev/screenshot with sync set to true, decode the Base64 body with base64_decode and write the bytes to a .png file. It is a full-page capture from real Chrome for 1 credit; leave sync out and the result goes to your webhook instead.

Free plan, no credit card. 1,000 credits a month.

One POST to /screenshot loads the page in real Chrome, scrolls it top to bottom so lazy images load, and captures the whole document — not just the fold. The image comes back Base64-encoded in a text/plain body, so the PHP work is two lines: decode it with base64_decode and write the bytes.

The request below also sets page_options.block_cookie_banners, because a consent dialog over the page is the most common reason a screenshot is useless. Every other knob — viewport, device scale, JPEG or WebP, one element by selector, dark mode — goes in screenshot_options.

Setup

Before you start

Nothing to install beyond PHP itself: the curl extension ships with it. Check it is loaded, and put your API key in the environment.

Terminal
php -m | grep curl   # prints "curl"
export URLPIPE_API_KEY="your_api_key"

The request

Save a screenshot as a PNG file

Without CURLOPT_RETURNTRANSFER, curl_exec() prints the body and returns true — the most common reason a PHP example "returns nothing". curl_exec() returns false only when there was no HTTP answer at all; a 422 is still a string, so read the status too. The body is the image as Base64 text; base64_decode() gives the bytes back.

screenshot.php
<?php

function fail(string $message): never
{
    fwrite(STDERR, $message . "\n");
    exit(1);
}

$ch = curl_init("https://urlpipe.dev/screenshot");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    // Return the body from curl_exec() instead of printing it.
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode(["url" => "https://example.com", "page_options" => ["block_cookie_banners" => true], "sync" => true]),
    // A sync call can take up to 60 s; curl would otherwise wait forever.
    CURLOPT_TIMEOUT => 90,
]);
$body = curl_exec($ch);
if ($body === false) {
    fail("Request failed: " . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}

$png = base64_decode($body);
file_put_contents("screenshot.png", $png);
echo "Saved screenshot.png (" . strlen($png) . " bytes)\n";

Run it: php screenshot.php

Async

The async variant: a token, a webhook and a poll

Leave out sync and the answer is a token, straight away. send() uses CURLOPT_CUSTOMREQUEST so one function makes both the POST and the GETs, and array destructuring ([$status, $body] = …) keeps the loop short.

screenshot_async.php
<?php

const API = "https://urlpipe.dev";

function fail(string $message): never
{
    fwrite(STDERR, $message . "\n");
    exit(1);
}

// One request to the API: returns [status, body].
function send(string $method, string $path, ?array $payload = null): array
{
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
            "Content-Type: application/json",
        ],
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $body = curl_exec($ch);
    if ($body === false) {
        fail("Request failed: " . curl_error($ch));
    }
    return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), $body];
}

// No "sync": the request is accepted at once and the work carries on without you.
[$status, $body] = send("POST", "/screenshot", [
    "url" => "https://example.com",
    "page_options" => ["block_cookie_banners" => true],
    "report_to" => "https://your-app.com/webhooks/urlpipe",
    "labels" => ["customer" => "acme"],
]);
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}
$token = json_decode($body, true)["token"];
echo "Accepted {$token}\n";

// The result is POSTed to report_to when it is ready. Polling by token is the
// other way to collect it: no endpoint needed, and a backup for the webhook.
for ($attempt = 0; $attempt < 60; $attempt++) {
    [$status, $body] = send("GET", "/result/{$token}");
    if ($status !== 202) { // 202 means still processing
        break;
    }
    sleep(2);
}
if ($status === 202) {
    fail("Still processing after two minutes; try the token again later.");
}
if ($status === 422) {
    fail("The analysis failed: " . json_decode($body, true)["error"]);
}
if ($status === 410) {
    fail("The result is past the 30-day window; send the request again.");
}
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}

$png = base64_decode($body);
file_put_contents("screenshot.png", $png);
echo "Saved screenshot.png (" . strlen($png) . " bytes)\n";

Run it: php screenshot_async.php

Errors

Handle errors and retries

json_decode() returns null for a body that is not JSON (a 401 answers in plain text), and ?: [] turns that into an empty array. CURLOPT_HEADERFUNCTION is how curl hands you response headers one line at a time.

screenshot_errors.php
<?php

final class URLpipeError extends RuntimeException
{
}

// POST a sync request and return the result body, or throw URLpipeError.
function urlpipe(string $path, array $payload, int $attempts = 5): string
{
    for ($attempt = 0; $attempt < $attempts; $attempt++) {
        $headers = [];
        $ch = curl_init("https://urlpipe.dev{$path}");
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
                "Content-Type: application/json",
            ],
            CURLOPT_POSTFIELDS => json_encode($payload + ["sync" => true]),
            CURLOPT_TIMEOUT => 90,
            // Collect the response headers: Retry-After is the one needed here.
            CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$headers): int {
                [$name, $value] = array_pad(explode(":", $line, 2), 2, "");
                $headers[strtolower(trim($name))] = trim($value);
                return strlen($line);
            },
        ]);
        $body = curl_exec($ch);
        if ($body === false) {
            throw new URLpipeError("network error: " . curl_error($ch));
        }
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($status === 200) {
            return $body;
        }
        if ($status === 401) {
            throw new URLpipeError("401: the API key is missing or wrong. Check URLPIPE_API_KEY.");
        }

        $error = json_decode($body, true) ?: [];
        $code = $error["error"] ?? "";
        $detail = isset($error["message"]) ? "{$code}: {$error["message"]}" : $code;

        if ($status === 429 && $code === "rate_limited") {
            // Sending too fast: Retry-After says how long the window has left.
            sleep((int) ($headers["retry-after"] ?? 1));
        } elseif ($status === 429 && $code === "concurrency_limit") {
            // Every parallel slot on your plan is busy with your own requests.
            sleep(2 ** $attempt);
        } elseif ($status === 504) {
            // Still running on our side; the token collects it from GET /result/:token.
            throw new URLpipeError("504 processing_timeout: collect it later with token {$error["token"]}");
        } else {
            // 403 email_unverified, 422 (a bad parameter, or a page that would not load),
            // 429 quota_exceeded: sending the same request again gets the same answer.
            throw new URLpipeError("{$status}: {$detail}");
        }
    }
    throw new URLpipeError("429: still refused after {$attempts} attempts");
}

try {
    $body = urlpipe("/screenshot", ["url" => "https://example.com", "page_options" => ["block_cookie_banners" => true]]);
} catch (URLpipeError $e) {
    fwrite(STDERR, "URLpipe: {$e->getMessage()}\n");
    exit(1);
}

$png = base64_decode($body);
file_put_contents("screenshot.png", $png);
echo "Saved screenshot.png (" . strlen($png) . " bytes)\n";

Run it: php screenshot_errors.php

Details

What to know about /screenshot

  • The default viewport is 1350 × 797 and the capture follows the page down to 16,384 px; a taller page is cut there.
  • Every response carries an X-Result-Url header: a link to the same image that needs no API key and stays valid for 30 days. Often you can store that link instead of the file.
  • PNG is the default; "format": "jpeg" or "webp" in screenshot_options makes a long page far smaller.
  • It captures images, not PDFs, and it does not record video.
  • A screenshot of the same URL with the same options is served from the cache for 7 days by default, free. Set max_age to refresh sooner.

Other languages

Take a screenshot of a website in another language

More PHP: every PHP recipe

FAQ

Frequently asked questions

Why is the screenshot response Base64 and not an image?
So the same body works in JSON, in a webhook payload and in an <img> data URI. Decode it with base64_decode, or skip decoding and use the X-Result-Url header, a direct link to the image.
How do I take a mobile screenshot?
Set screenshot_options.viewport_width to a phone width such as 390 and device_scale_factor to 2 or 3. The viewport can be anything from 320 to 1920 pixels wide.
Can I screenshot one element instead of the whole page?
Yes: screenshot_options takes a CSS selector and captures just that element. A selector that matches nothing is a 422, and costs nothing.
Do I need an SDK to call URLpipe from PHP?
No Composer package: the curl extension is part of PHP, and the API is one POST per job.

Get a key and run it.

Free plan, no card. Paste your key into URLPIPE_API_KEY and every program on this page runs as it is.