PHP Screenshot API Tutorial: cURL, Guzzle, Laravel and WordPress
Working PHP code for the Screenshotly screenshot API: a cURL quick start, Guzzle with streaming and Retry-After handling, Laravel queued jobs, a WordPress plugin and signed webhooks.
PHP still runs a large share of the web, so it is a common place to need screenshots: Open Graph images for a Laravel app, thumbnails for a WordPress directory, or PDF snapshots of invoices. This guide shows how to call the Screenshotly API from plain PHP, Guzzle, Symfony, Laravel and WordPress.
Every request body below was checked against the API's request schema, and every snippet was run against a local mock of the API, including the retry and error paths.
The API contract in one table
| Endpoint | POST https://screenshotly.app/api/screenshot |
| Authentication | x-api-key: YOUR_API_KEY header (Authorization: Bearer YOUR_API_KEY also works) |
| Body | JSON. Only url is required. Unknown fields are rejected with 400. |
| Success | 200 with the file as the body (image/png, image/jpeg, image/webp, application/pdf, …) |
| Errors | JSON {"error": "...", "message": "..."} with 400, 401, 403, 413, 429, 500 or 503 |
The full parameter list is in the screenshot API reference. Get a key from the dashboard after you sign up; the Free plan includes 100 captures in total, and failed captures do not count.
Store the key in an environment variable or your framework's secrets. Never ship it to a browser.
Quick start: the cURL extension
The cURL extension ships with almost every PHP build, so this works with no Composer packages:
<?php
const SCREENSHOTLY_ENDPOINT = 'https://screenshotly.app/api/screenshot';
/**
* Capture a URL and write the image to $outputPath.
* Throws RuntimeException with the API's JSON error message on failure.
*/
function captureScreenshot(string $url, string $outputPath, array $options = []): void
{
$apiKey = getenv('SCREENSHOTLY_API_KEY');
if ($apiKey === false || $apiKey === '') {
throw new RuntimeException('Set SCREENSHOTLY_API_KEY');
}
$payload = json_encode(array_merge([
'url' => $url,
'device' => 'desktop',
'format' => 'png',
], $options), JSON_THROW_ON_ERROR);
$ch = curl_init(SCREENSHOTLY_ENDPOINT);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'x-api-key: ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => $payload,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60, // slow pages can take tens of seconds
]);
$body = curl_exec($ch);
if ($body === false) {
$error = curl_error($ch);
throw new RuntimeException("Network error: $error");
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
$error = json_decode($body, true);
$message = $error['message'] ?? $error['error'] ?? 'Unknown error';
throw new RuntimeException("Screenshotly returned HTTP $status: $message", $status);
}
file_put_contents($outputPath, $body);
}
// Usage
captureScreenshot('https://example.com', 'example.png');
echo "Saved example.png\n";
Two details matter here. First, a non-200 response has a JSON body, so the function decodes it and puts the API's message in the exception instead of writing an error document to example.png. Second, a capture can take tens of seconds on a slow page (page navigation alone may use up to 30 seconds), so the client timeout is 60 seconds. For pages that are slower than that, use the async jobs API.
Guzzle: streaming and Retry-After
For application code, use Guzzle 7:
composer require guzzlehttp/guzzle:^7
This client streams the image to disk with the sink option and retries with Middleware::retry:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
final class Screenshotly
{
private const MAX_RETRIES = 3;
private const MAX_WAIT_SECONDS = 60;
private Client $http;
public function __construct(string $apiKey)
{
$stack = HandlerStack::create();
$stack->push(Middleware::retry(
// Decide: retry 429 (when the wait is short), 500 and 503.
function (int $retries, RequestInterface $request, ?ResponseInterface $response = null, $exception = null): bool {
if ($retries >= self::MAX_RETRIES || $response === null) {
return false;
}
$status = $response->getStatusCode();
if ($status === 429) {
// A quota-exhausted 429 can ask you to wait days. Fail fast instead.
return self::retryAfter($response) <= self::MAX_WAIT_SECONDS;
}
return in_array($status, [500, 503], true);
},
// Delay in milliseconds: honour Retry-After, otherwise back off 1s, 2s, 4s.
function (int $retries, ?ResponseInterface $response = null): int {
if ($response !== null && $response->hasHeader('Retry-After')) {
return self::retryAfter($response) * 1000;
}
return (2 ** ($retries - 1)) * 1000;
}
));
$this->http = new Client([
'base_uri' => 'https://screenshotly.app',
'handler' => $stack,
'headers' => ['x-api-key' => $apiKey],
'connect_timeout' => 10,
'timeout' => 60,
]);
}
/** Stream the capture straight to $path instead of holding it in memory. */
public function captureToFile(string $url, string $path, array $options = []): void
{
try {
$this->http->post('/api/screenshot', [
'json' => ['url' => $url] + $options + ['format' => 'png'],
'sink' => $path,
]);
} catch (RequestException $e) {
// On an error status the sink holds the JSON error body, not an image.
@unlink($path);
$response = $e->getResponse();
$error = $response ? json_decode((string) $response->getBody(), true) : null;
throw new RuntimeException(
'Capture failed: ' . ($error['message'] ?? $error['error'] ?? $e->getMessage()),
$response ? $response->getStatusCode() : 0,
$e
);
}
}
private static function retryAfter(ResponseInterface $response): int
{
return (int) ($response->getHeaderLine('Retry-After') ?: 1);
}
}
// Usage
$client = new Screenshotly(getenv('SCREENSHOTLY_API_KEY'));
$client->captureToFile('https://example.com', 'example-full.png', [
'fullPage' => true,
'width' => 1440,
'height' => 900,
]);
echo "Saved example-full.png\n";
The retry rules follow how the API behaves:
- 429 with a short
Retry-After: you hit the per-minute request limit (Free 5, Basic 40, Growth 80, Scale 200). Waiting the stated number of seconds and retrying is correct. - 429 with a long
Retry-After: the plan's capture quota is used up, and the header points at the reset time, which can be days away. The decider gives up instead of putting a worker to sleep. - 500 and 503: the capture failed or the regional proxy was unavailable. A short backoff and retry is reasonable.
- 400, 401, 403 and 413 are not retried. They fail the same way every time: invalid options, a bad key, a feature your plan does not include, or a body larger than 64 KB.
Capture options that matter in PHP projects
Options are top-level JSON fields. Some need a paid plan; when you send one your plan does not include, the API returns 403 with "error": "Plan upgrade required" and a minimumPlan field.
| Goal | Fields | Plan |
|---|---|---|
| Custom viewport | width (320–3840), height (240–3840), or device: desktop, laptop, tablet, mobile |
All |
| Whole page | fullPage: true |
All |
| Smaller files | format: "webp" or "jpeg" with quality (0–100) |
All |
| Hide ads | blockAds: true |
All |
| Wait for content | delay (ms, up to 10000), waitForSelector, waitForNetworkIdle |
All |
| One element | selector: "#pricing" |
All |
| PDF or HTML output | format: "pdf" or "html" |
Basic+ |
| Logged-in pages | headers, cookies |
Basic+ |
| Signed storage link instead of bytes | storage: {"enabled": true} |
Basic+ |
| Remove cookie banners and chat widgets | aiRemoval: {"enabled": true, "types": ["cookie-banner", "chat-widget"]} |
Growth+ |
| Device frame | mockup: "macbook-pro" (also iphone-14, ipad-pro, browser-light, browser-dark, browser-minimal) |
Growth+ |
PDF output is A4 with 1 cm margins; page size and margins are not configurable. See pricing for the plan comparison.
Symfony HttpClient
In a Symfony app, the built-in HttpClient can stream the response in chunks:
<?php
require 'vendor/autoload.php';
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::createForBaseUri('https://screenshotly.app', [
'headers' => ['x-api-key' => $_SERVER['SCREENSHOTLY_API_KEY']],
'timeout' => 60,
]);
$response = $client->request('POST', '/api/screenshot', [
'json' => ['url' => 'https://example.com', 'format' => 'webp', 'quality' => 80],
]);
if (200 !== $response->getStatusCode()) {
$error = $response->toArray(false); // decode the JSON error without throwing
throw new RuntimeException(sprintf('HTTP %d: %s', $response->getStatusCode(), $error['message'] ?? $error['error']));
}
// Write chunks as they arrive instead of buffering the whole image.
$file = fopen('example.webp', 'w');
foreach ($client->stream($response) as $chunk) {
fwrite($file, $chunk->getContent());
}
fclose($file);
echo "Saved example.webp\n";
If you add RetryableHttpClient, give it a custom retry strategy. Its default strategy retries 429s and waits for whatever Retry-After says, which for an exhausted quota can mean a worker sleeping for days. In a Messenger handler, you can get the same split as the Guzzle decider above by throwing RecoverableMessageHandlingException on a short 429 (the message is retried) and UnrecoverableMessageHandlingException on a long one (it goes straight to the failure transport).
Laravel: a service class and a queued job
Put the key in config:
<?php
// config/services.php
return [
'screenshotly' => [
'key' => env('SCREENSHOTLY_API_KEY'),
'webhook_secret' => env('SCREENSHOTLY_WEBHOOK_SECRET'),
],
];
The service returns the raw response so callers can decide how to treat each status. captureToFile() uses the HTTP client's sink() for large full-page captures:
<?php
// app/Services/Screenshotly.php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class Screenshotly
{
public function __construct(private string $apiKey)
{
}
/** Send a capture request and return the raw response; callers decide how to handle errors. */
public function capture(string $url, array $options = []): Response
{
return $this->http()->post('/api/screenshot', ['url' => $url] + $options + ['format' => 'png']);
}
/** Stream a large capture (full-page PNG, PDF) straight to a local path. */
public function captureToFile(string $url, string $path, array $options = []): void
{
$this->http()
->sink($path)
->post('/api/screenshot', ['url' => $url] + $options + ['format' => 'png'])
->throw();
}
private function http(): PendingRequest
{
return Http::baseUrl('https://screenshotly.app')
->withHeaders(['x-api-key' => $this->apiKey])
->connectTimeout(10)
->timeout(60);
}
}
<?php
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Services\Screenshotly;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(Screenshotly::class, fn () => new Screenshotly(config('services.screenshotly.key')));
}
}
Capture inside a queued job, never in a controller. The job retries server errors with backoff, releases itself back onto the queue after a short 429, and fails immediately on errors that a retry will not fix:
<?php
// app/Jobs/CapturePageScreenshot.php
namespace App\Jobs;
use App\Models\Page;
use App\Services\Screenshotly;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
class CapturePageScreenshot implements ShouldQueue
{
use Queueable;
public int $tries = 5; // release() counts as an attempt too
public int $timeout = 90;
public function __construct(public Page $page)
{
}
/** Seconds to wait before retrying after an exception (5xx, network). */
public function backoff(): array
{
return [10, 30, 90];
}
public function handle(Screenshotly $screenshotly): void
{
$response = $screenshotly->capture($this->page->url, [
'fullPage' => true,
'blockAds' => true,
]);
if ($response->status() === 429) {
$wait = (int) $response->header('Retry-After');
if ($wait > 3600) {
// Monthly quota is used up: retrying will not help until it resets.
$this->fail(new RuntimeException('Screenshotly quota exhausted: ' . $response->json('message')));
return;
}
$this->release(max(1, $wait));
return;
}
if ($response->clientError()) {
// 400, 401, 403 and 413 will fail the same way on every retry.
$this->fail($response->toException());
return;
}
$response->throw(); // 5xx: throw so the queue retries with backoff()
$path = "screenshots/{$this->page->id}.png";
Storage::disk('s3')->put($path, $response->body());
$this->page->update(['screenshot_path' => $path]);
}
}
Dispatch it when the page is created or its URL changes:
CapturePageScreenshot::dispatch($page);
Keep the worker's --timeout above the job's $timeout, and keep both above the 60-second HTTP timeout.
Slow pages, PDFs and batches: the async jobs API
On the Basic plan and above, POST /api/jobs accepts the same body as /api/screenshot but returns 202 straight away with a job ID. Screenshotly runs the capture, retries it on failure, and keeps the result for your account's retention period. Send an Idempotency-Key so a retried submit returns the original job instead of creating a second one:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$http = new Client([
'base_uri' => 'https://screenshotly.app',
'headers' => ['x-api-key' => getenv('SCREENSHOTLY_API_KEY')],
'timeout' => 20,
]);
// 1. Queue the capture. Reusing the same Idempotency-Key on a retry returns
// the original job instead of creating (and billing) a second one.
$queued = json_decode((string) $http->post('/api/jobs', [
'headers' => ['Idempotency-Key' => 'invoice-4821'],
'json' => ['url' => 'https://example.com/invoices/4821', 'format' => 'pdf'],
])->getBody(), true);
// 2. Poll the status URL until the job reaches a final state.
$deadline = time() + 300;
do {
sleep(2);
$job = json_decode((string) $http->get($queued['statusUrl'])->getBody(), true);
} while (in_array($job['status'], ['QUEUED', 'RUNNING'], true) && time() < $deadline);
if ($job['status'] !== 'SUCCEEDED') {
throw new RuntimeException("Job {$job['id']} ended as {$job['status']}");
}
// 3. resultUrl is a short-lived signed link: download it now, without the API key.
(new Client(['timeout' => 60]))->get($job['resultUrl'], ['sink' => 'invoice-4821.pdf']);
echo "Saved invoice-4821.pdf\n";
Job states are QUEUED, RUNNING, SUCCEEDED, FAILED and CANCELED. The resultUrl signature expires quickly; read the job again to get a fresh one. On Growth and Scale you can submit up to 20 captures at once with POST /api/jobs/batch and a {"captures": [...]} body. Details are in the async jobs reference.
Webhooks: verify the signature
Instead of polling, add webhook: {"url": "https://yourapp.com/webhooks/screenshotly", "secret": "..."} to a capture (Basic+). Screenshotly POSTs a JSON event and retries delivery up to five times. When you set a secret, the request carries X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body. Compare it with hash_equals(), which takes constant time:
<?php
/**
* Returns true when $rawBody was signed with $secret.
* Compute the HMAC over the raw request body, before any JSON decoding.
*/
function isValidScreenshotlySignature(string $rawBody, ?string $header, string $secret): bool
{
if ($header === null || !str_starts_with($header, 'sha256=')) {
return false;
}
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
return hash_equals($expected, $header);
}
// Plain PHP endpoint
$raw = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SCREENSHOTLY_SIGNATURE'] ?? null;
if (!isValidScreenshotlySignature($raw, $signature, getenv('SCREENSHOTLY_WEBHOOK_SECRET'))) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
if ($event['event'] === 'screenshot.completed') {
// $event['data'] holds url, format, size, duration and, when you
// requested storage, a signed storageUrl.
error_log('Captured ' . $event['data']['url']);
}
http_response_code(204);
The Laravel version. Register it in routes/api.php, which has no CSRF middleware, or exclude the path from CSRF verification:
<?php
// app/Http/Controllers/ScreenshotlyWebhookController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class ScreenshotlyWebhookController
{
public function __invoke(Request $request)
{
$expected = 'sha256=' . hash_hmac('sha256', $request->getContent(), config('services.screenshotly.webhook_secret'));
abort_unless(hash_equals($expected, (string) $request->header('X-Screenshotly-Signature')), 401);
if ($request->input('event') === 'screenshot.completed') {
Log::info('Screenshot ready', $request->input('data'));
}
return response()->noContent();
}
}
WordPress: capture on publish
This plugin captures a screenshot of a post's source_url custom field when the post is first published. The capture runs in a scheduled event, so the editor's save request is not held up, and the key lives in wp-config.php instead of the options table:
<?php
/**
* Plugin Name: Screenshotly Post Screenshots
* Description: Captures a screenshot of each published post's source URL in the background.
*/
// In wp-config.php, outside the database and version control:
// define('SCREENSHOTLY_API_KEY', 'your-key');
const SCREENSHOTLY_ENDPOINT = 'https://screenshotly.app/api/screenshot';
/** @return string|WP_Error Image bytes or an error carrying the HTTP status. */
function screenshotly_capture(string $url, array $options = [])
{
$response = wp_remote_post(SCREENSHOTLY_ENDPOINT, [
'timeout' => 60,
'headers' => [
'x-api-key' => SCREENSHOTLY_API_KEY,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode(array_merge(['url' => $url, 'format' => 'png'], $options)),
]);
if (is_wp_error($response)) {
return $response; // DNS, TLS or timeout problem
}
$status = (int) wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if (200 !== $status) {
$error = json_decode($body, true);
return new WP_Error('screenshotly_http_' . $status, $error['message'] ?? $error['error'] ?? 'Capture failed', [
'status' => $status,
'retry_after' => (int) wp_remote_retrieve_header($response, 'retry-after'),
]);
}
return $body;
}
// Queue the capture on first publish so the editor's save request is not blocked.
add_action('transition_post_status', function ($new_status, $old_status, $post) {
if ('publish' === $new_status && 'publish' !== $old_status) {
wp_schedule_single_event(time(), 'screenshotly_capture_post', [$post->ID]);
}
}, 10, 3);
add_action('screenshotly_capture_post', function ($post_id) {
$source = get_post_meta($post_id, 'source_url', true);
if (!$source) {
return;
}
$image = screenshotly_capture($source, ['blockAds' => true, 'width' => 1280, 'height' => 800]);
if (is_wp_error($image)) {
$data = $image->get_error_data();
$retryAfter = $data['retry_after'] ?? 0;
// Per-minute limit: try again later. Quota exhausted (long Retry-After): give up and log.
if (429 === ($data['status'] ?? 0) && $retryAfter <= HOUR_IN_SECONDS) {
wp_schedule_single_event(time() + max(60, $retryAfter), 'screenshotly_capture_post', [$post_id]);
}
error_log("Screenshotly capture failed for post $post_id: " . $image->get_error_message());
return;
}
$upload = wp_upload_bits("screenshot-{$post_id}.png", null, $image);
if ($upload['error']) {
error_log("Could not save screenshot for post $post_id: {$upload['error']}");
return;
}
update_post_meta($post_id, 'screenshot_url', esc_url_raw($upload['url']));
});
WP-Cron runs only when someone loads a page, so on a quiet site the event can fire late. For anything time-sensitive, set define('DISABLE_WP_CRON', true); and run wp cron event run --due-now from a system cron, or use Action Scheduler if your site already has it.
Error reference
| Status | Meaning | What PHP code should do |
|---|---|---|
| 400 | Invalid JSON, unknown field, out-of-range value, or a URL that is not public | Fix the request; do not retry |
| 401 | Missing or invalid API key | Check the env var or secret; do not retry |
| 403 | Feature needs a higher plan (minimumPlan in the body) |
Remove the option or upgrade; do not retry |
| 413 | Request body over 64 KB | Trim javascript, headers or cookies |
| 429 | Per-minute limit (short Retry-After) or quota used up (long Retry-After) |
Retry after a short wait; fail on a long one |
| 500 | The page could not be captured | Retry with backoff a few times |
| 503 | The regional capture proxy is unavailable | Retry later |
Checklist before production
- The API key comes from the environment, Laravel config or
wp-config.php, never from code or the browser. - Captures run in a queue or scheduled event, not inside a web request.
- The HTTP timeout is about 60 seconds, and your queue's job timeout is higher.
- Large captures stream to disk with
sink. - 429 handling checks how long
Retry-Afteris before waiting. - Slow pages and PDFs go through
/api/jobs(Basic+). - Webhook endpoints verify
X-Screenshotly-Signaturewithhash_equals().
Ready to add screenshots to your PHP app?
Get your free API key →. The Free plan includes 100 captures.
See also:
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Should I use cURL or Guzzle for PHP screenshot integration?
The cURL extension is fine for scripts and has no dependencies. For application code, use Guzzle 7 (or Laravel's HTTP client, which wraps it): its retry middleware and sink option give you Retry-After handling and streaming to disk without hand-written plumbing.
How do I avoid blocking PHP-FPM workers with screenshot capture?
Run captures in a queued job: Laravel queues, Symfony Messenger, or a scheduled event in WordPress. A capture can take tens of seconds on a slow page, and an FPM worker waiting on it cannot serve other requests. For slow pages, PDFs and batches, the Screenshotly async jobs API (Basic plan and above) moves the waiting off your side entirely.
Why does my Guzzle call run out of memory on large captures?
getBody()->getContents() loads the whole response into a PHP string. Pass Guzzle's sink option (a file path or stream) so the body is written to disk as it arrives. In Laravel, the HTTP client exposes the same thing as ->sink($path).
How should PHP code handle a 429 from Screenshotly?
Read the Retry-After header. A short value means you hit the per-minute limit (5, 40, 80 or 200 requests per minute depending on plan), so wait and retry. A very long value means the plan's capture quota is used up, so fail the job and alert rather than sleeping.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.