How to take a website screenshot in PHP

By URLBooth · Published · Last updated

To take a website screenshot in PHP, use the cURL extension to send an authenticated POST to the URLBooth endpoint /v1/screenshots with a JSON body containing the page URL and an Authorization: Bearer key. The response body is the image, so you check the HTTP status and write the returned string to a file.

What is the minimal PHP example with cURL?

This script uses only the cURL extension, which ships enabled with most PHP builds. Export URLBOOTH_API_KEY and run it with php screenshot.php. The API needs the Pro plan; keys are created in the dashboard under API keys.

PHP cURL example
<?php
​
$ch = curl_init("https://urlbooth.com/v1/screenshots");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("URLBOOTH_API_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode(["url" => "https://example.com"]),
]);
​
$body = curl_exec($ch);
​
if ($body === false) {
throw new RuntimeException("cURL error: " . curl_error($ch));
}
​
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
​
if ($status !== 200) {
$error = json_decode($body, true)["error"] ?? ["code" => "unknown", "message" => "HTTP $status"];
throw new RuntimeException("{$error['code']}: {$error['message']}");
}
​
file_put_contents("screenshot.png", $body);
echo "saved screenshot.png\n";

CURLOPT_RETURNTRANSFER is the line people forget. Without it, curl_exec prints the response straight to output and returns true, so you would be writing the string "1" into your PNG. With it, curl_exec returns the body as a string, or false if the transfer itself failed (DNS, connection, timeout). Those two outcomes are different: false means no HTTP response at all, while a string with a 4xx or 5xx status is a response from the API.

How do you check the HTTP status with curl_getinfo?

cURL does not treat an HTTP error as a failure, so curl_exec happily returns a JSON error body. Read the status with curl_getinfo($ch, CURLINFO_HTTP_CODE) before you touch the body, and only write the file on 200. On any other status the body is JSON shaped as {"error": {"code", "message", "requestId"}}, which you parse with json_decode($body, true). The examples do not call curl_close: it has done nothing since PHP 8.0 and is deprecated in PHP 8.5.

Set both timeouts. CURLOPT_CONNECTTIMEOUT bounds connecting, and CURLOPT_TIMEOUT bounds the whole call. Captures take a few seconds and the server stops at about 45, so 60 is a safe ceiling. Also remember PHP's own max_execution_time: under a web server it often defaults to 30 seconds, which would kill the request before cURL does. Run captures from a queue worker or CLI script rather than inline in a page request.

How do you set the device, format, full page, cleanup and frame?

Build a PHP array and pass it through json_encode. The fields are url, device, format (png, jpeg or webp), fullPage, cleanup and frame. Use real PHP booleans (true, not "true"), because a string where the API expects a boolean is a 400. Unknown fields are also rejected. Device ids such as ipad-air-11, iphone-17-pro and macbook-pro-14 are listed in the API docs. Frames are disabled for full-page captures.

Device, format and frame
<?php
​
$payload = [
"url" => "https://example.com",
"device" => "ipad-air-11",
"format" => "webp",
"frame" => true,
"cleanup" => true,
];
​
$ch = curl_init("https://urlbooth.com/v1/screenshots");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("URLBOOTH_API_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode($payload),
]);
​
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
​
if ($body === false || $status !== 200) {
throw new RuntimeException("Capture failed with HTTP $status");
}
​
file_put_contents("pricing.webp", $body);

How do you read X-Screenshot-Id and download the image later?

Response headers are not returned by default. Use CURLOPT_HEADERFUNCTION, which cURL calls once per header line, to collect them, and return the line length so cURL keeps going. The X-Screenshot-Id value identifies the stored copy, which is kept for two days (X-Expires-At gives the exact time).

Collect response headers
<?php
​
$responseHeaders = [];
​
$ch = curl_init("https://urlbooth.com/v1/screenshots");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("URLBOOTH_API_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode(["url" => "https://example.com"]),
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$responseHeaders) {
$parts = explode(":", $line, 2);
if (count($parts) === 2) {
$responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
​
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
​
if ($body === false || $status !== 200) {
throw new RuntimeException("Capture failed with HTTP $status");
}
​
file_put_contents("screenshot.png", $body);
echo $responseHeaders["x-screenshot-id"] ?? "", "\n";

To download the capture again, GET /v1/screenshots/{id}/image with the same key.

Download a stored screenshot
<?php
​
$id = $argv[1]; // the X-Screenshot-Id value from an earlier capture
​
$ch = curl_init("https://urlbooth.com/v1/screenshots/" . rawurlencode($id) . "/image");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("URLBOOTH_API_KEY"),
],
]);
​
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
​
if ($body === false || $status !== 200) {
throw new RuntimeException("Download failed with HTTP $status");
}
​
file_put_contents("again.png", $body);

Is there a shorter way in Laravel?

Yes. Laravel's Http facade wraps cURL and handles JSON for you. Put the key in .env, expose it through config/services.php (so it still works when config is cached) and call it like this. Use $response->body() for the raw image, not json(). Note the retry callback only retries the status codes worth retrying.

Laravel Http facade
use Illuminate\Support\Facades\Http;
​
$response = Http::withToken(config('services.urlbooth.key'))
->timeout(60)
->retry(3, 2000, fn ($exception) => in_array($exception->getCode(), [429, 503, 504]), throw: false)
->post('https://urlbooth.com/v1/screenshots', [
'url' => 'https://example.com',
'device' => 'desktop',
]);
​
if ($response->failed()) {
$error = $response->json('error');
throw new RuntimeException($error['code'] . ': ' . $error['message']);
}
​
file_put_contents(storage_path('app/screenshot.png'), $response->body());

How do you handle errors and rate limits in PHP?

Pro allows 60 requests per minute, 10 concurrent captures and 10,000 per day. A 429 rate_limited carries a Retry-After header in seconds; daily_limit_reached is also a 429 but resets at 00:00 UTC, so retrying immediately is pointless. Retry 503 capture_unavailable and 504 capture_timeout with backoff. Fix the request instead of retrying a 400, 401 or 402. A 502 capture_failed means the target site blocked or broke the capture. Log requestId so a failure can be traced.

Retry helper
<?php
​
function capture(array $payload, int $attempts = 3): string
{
for ($attempt = 1; ; $attempt++) {
$retryAfter = null;
$ch = curl_init("https://urlbooth.com/v1/screenshots");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("URLBOOTH_API_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, "retry-after:") === 0) {
$retryAfter = (int) trim(substr($line, 12));
}
return strlen($line);
},
]);
​
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
​
if ($body !== false && $status === 200) {
return $body;
}
​
$retryable = $body === false || in_array($status, [429, 503, 504], true);
if (!$retryable || $attempt === $attempts) {
$error = json_decode((string) $body, true)["error"] ?? [];
throw new RuntimeException(
($error["code"] ?? "http_$status") . " " . ($error["requestId"] ?? "")
);
}
​
sleep($retryAfter ?: 2 ** $attempt);
}
}
​
file_put_contents("screenshot.png", capture(["url" => "https://example.com"]));

PHP runs one request at a time per process, so concurrency comes from running several queue workers. Keep it at ten or fewer in total.

When should you run a headless browser yourself instead?

If you need to log in, drive a flow or capture internal pages, a local headless browser such as Chromium driven from Node is the right tool, and that is awkward to host next to a typical PHP app. For public URLs, the API keeps browser binaries out of your PHP deployment. The trade-offs are written up in screenshot API vs running Puppeteer yourself.

Where to go next