How to Set a Timeout for HTML-to-PDF Requests in PHP
Configure PHP HTML-to-PDF timeouts correctly for HTTP APIs, local renderers, retries, browser readiness, and hosting limits.

Set the timeout on the layer that is waiting. When PHP calls a remote HTML-to-PDF API, configure the HTTP client. When PHP starts a local renderer such as Chromium, configure the child process. These limits are separate from PHP’s execution limit, a reverse proxy timeout, a queue-worker deadline, and any timeout enforced by the PDF service.
For Symfony HttpClient, use timeout for an idle period and max_duration for the complete HTTP transaction:
<?php
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
$client = HttpClient::create();
try {
$response = $client->request('POST', $pdfServiceUrl, [
'timeout' => 10.0,
'max_duration' => 45.0,
'json' => [
'html' => $html,
],
]);
// Response consumption can throw too because responses are lazy.
$status = $response->getStatusCode();
$pdf = $response->getContent();
file_put_contents(__DIR__ . '/output.pdf', $pdf);
} catch (TransportExceptionInterface $e) {
error_log('PDF request failed or timed out: ' . $e->getMessage());
throw $e;
}
The values above are examples, not universal recommendations. Choose them from observed conversion latency, HTML complexity, asset behavior, and your caller’s deadline. Symfony’s documentation uses 2.5 seconds as an illustrative idle-timeout value; it is not a PDF-generation standard.
Understand which timeout you need
| Waiting layer | What it limits | Typical control |
|---|---|---|
| HTTP inactivity | How long the HTTP transaction may remain idle between data events | Symfony timeout |
| Complete HTTP call | Total request and response wall-clock time | Symfony max_duration |
| Connection setup | DNS, TCP, and TLS establishment | max_connect_duration where supported |
| Local renderer | Runtime of a Chromium or wkhtmltopdf child process | Symfony Process setTimeout() |
| PHP request | Overall PHP script execution and connection handling | PHP and hosting configuration |
| Proxy or web server | How long an upstream response may take | Reverse-proxy or web-server settings |
These controls do not automatically change one another. Increasing an HTTP timeout cannot extend a web server that closes the upstream connection after a shorter period. Likewise, changing a PHP execution limit does not change a renderer process timeout.
Remote HTML-to-PDF APIs with Symfony HttpClient
Idle timeout versus total duration
Symfony defines timeout as an inactivity limit. A connection can stay open longer when data continues arriving without an excessive pause. Use max_duration when the business requirement is “this conversion must finish within a fixed wall-clock budget,” regardless of intermittent progress.

$response = $client->request('POST', $pdfServiceUrl, [
'timeout' => 15.0, // maximum idle period
'max_duration' => 90.0, // complete request/response budget
'body' => [
'files' => fopen($htmlFile, 'r'),
],
]);
max_connect_duration is intended to bound DNS resolution, TCP connection, and TLS handshake time. Current Symfony documentation marks it as introduced in Symfony 8.1, so check the version installed in your project before using it. If your version does not expose an option, follow that version’s documentation rather than copying a newer configuration.
Catch failures while consuming the response
Symfony responses are lazy. A transport error may occur during request(), while reading the status, or while retrieving the PDF body. Put the exception handler around all of those operations, as in the first example. Do not assume that successfully creating a response object means the conversion succeeded.
Native PHP cURL
If you are not using Symfony, cURL separates connection and transfer limits. The exact API fields depend on your PDF provider, but the timeout structure looks like this:
<?php
$ch = curl_init($pdfServiceUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'html' => $html,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 90,
]);
$pdf = curl_exec($ch);
if ($pdf === false) {
throw new RuntimeException('PDF request failed: ' . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status < 200 || $status >= 300) {
throw new RuntimeException('PDF service returned HTTP ' . $status);
}
file_put_contents(__DIR__ . '/output.pdf', $pdf);
CURLOPT_CONNECTTIMEOUT covers connection establishment. CURLOPT_TIMEOUT caps the whole transfer. Keep the distinction when diagnosing whether a failure occurs before the service accepts the request or while it renders the document.
Local renderers with Symfony Process
If PHP launches a renderer executable, the HTTP client’s settings are irrelevant. Symfony Process documents a default process timeout of 60 seconds. Set your own value and handle ProcessTimedOutException.
<?php
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;
$process = new Process([
'/usr/bin/chromium',
'--headless',
'--no-sandbox',
'--disable-gpu',
'--print-to-pdf=' . __DIR__ . '/output.pdf',
$url,
]);
$process->setTimeout(90.0);
try {
$process->mustRun();
} catch (ProcessTimedOutException $e) {
error_log('Renderer exceeded its process timeout');
throw $e;
}
The documented 60-second default is a Symfony Process default, not a guarantee shared by every PDF renderer. With asynchronous execution, Symfony says your application must call checkTimeout() regularly; otherwise a timeout may not be detected promptly.
Browser readiness and network-idle waits
A renderer can spend most of its time waiting for fonts, images, JavaScript, or browser network activity. Gotenberg’s Chromium conversion API supports waits based on browser network-idle events and cautions that waiting for all connections to close can be unsuitable for pages with long-polling or analytics connections.
A client timeout cannot make an unsuitable readiness condition succeed. If a page keeps a persistent connection open, use a readiness rule that matches the page, such as a specific selector or a bounded delay where your converter supports it. Then set the outer HTTP and process budgets long enough to include that readiness phase.
Retries and total elapsed time
Retries change the time your caller may wait. A 30-second per-attempt timeout with three attempts and backoff can exceed two minutes. Symfony’s retry behavior and supported status codes vary by version and method, so inspect the documentation for your installed version.
Budget retries explicitly:
- Set a maximum number of attempts.
- Set a per-attempt connect and transfer or idle timeout.
- Include backoff delays in the caller’s overall deadline.
- Retry only failures that are safe to repeat. A conversion request should be idempotent or carry a request identifier if the service supports one.
- Stop retrying when the remaining application deadline is shorter than another attempt.
Align every outer deadline
Trace the request from the browser or queue through PHP, your HTTP client, the PDF service, and any renderer. The smallest limit wins. Check:
- PHP execution and connection-handling settings.
- PHP-FPM or another application-worker timeout.
- Load balancer and reverse-proxy upstream timeouts.
- Queue-worker job limits.
- PDF service conversion limits.
- Symfony HttpClient or cURL settings.
- Symfony Process timeout when using a local executable.
The PHP manual describes connection handling when PHP’s imposed time limit is reached, but the exact behavior depends on your runtime and deployment. Verify the values in your own hosting, web-server, and proxy configuration.
Or skip the browser setup
If your goal is a reliable capture pipeline rather than maintaining Chromium, ScreenshotNeo provides a GET-based screenshot API and an MCP server for AI agents. The request is deliberately small:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo API documentation for request and response details. Before capture, ScreenshotNeo accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed as clean shots; response headers identify the page verdict and whether it was billed.
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Free accounts include 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Timeout troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Timeout occurs during connection | DNS, TCP, or TLS is slow or unreachable | Use a connection timeout, verify DNS and outbound firewall rules, and inspect max_connect_duration support. |
| Timeout occurs after regular progress | The idle limit is not the right control | Increase or remove the idle constraint carefully and set a suitable max_duration. |
| Request returns but reading content fails | Lazy response consumption encountered a transport error | Catch transport exceptions around status, headers, and body access. |
| Local process stops at 60 seconds | Symfony Process default timeout | Call setTimeout() and handle ProcessTimedOutException. |
| Renderer never becomes ready | Long-polling, analytics, blocked assets, or an endless network-idle wait | Change the renderer’s readiness condition and inspect page requests. |
| PHP reports success but the client sees a gateway error | Proxy or web-server deadline is shorter than PHP’s | Align upstream timeouts or move conversion to an asynchronous worker. |
| Retries make incidents worse | Per-attempt limits were mistaken for a total budget | Cap attempts and calculate timeout plus backoff against the caller deadline. |
| PDF is incomplete despite a long timeout | Missing assets, authentication, JavaScript errors, or an early print event | Inspect renderer logs and page readiness; a larger timeout does not repair content failures. |
Performance, reliability, and cost considerations
Measure conversion time by document type: static HTML, pages with remote images, JavaScript-heavy applications, authenticated pages, and large documents. Record connection time, time to first response, total conversion time, response size, and timeout reason. Use those observations to choose budgets rather than copying a number from an example.
For reliability, keep the PDF conversion outside a short interactive request when documents are expensive. Queue the job, persist its status, and let the client poll or receive a callback if your service supports that pattern. Make retries bounded and observable. Log the URL or document identifier, timeout layer, attempt number, and renderer or HTTP error without logging secrets embedded in URLs or headers.
For cost, retries may create multiple billable conversions with a hosted provider. Cache deterministic documents where appropriate, but invalidate the cache when source data changes. ScreenshotNeo identifies cache hits in its response and does not bill them; its paid plans include every feature, with yearly billing providing two months free.
Implementation checklist
- Identify whether PHP waits on HTTP, a local process, or both.
- Choose idle and total-duration semantics deliberately.
- Check Symfony version support for each option.
- Catch errors while consuming lazy responses.
- Configure the child-process timeout independently.
- Match browser readiness rules to the page’s network behavior.
- Include retries and backoff in the total deadline.
- Verify PHP, worker, proxy, and service limits.
- Log timeout layer and attempt number for diagnosis.
- Test slow assets, authentication, long-lived connections, and large HTML.
FAQ
Is timeout a maximum total request time in Symfony?
No. It controls HTTP inactivity. Use max_duration to cap the complete request and response.
Does changing PHP’s execution limit change Symfony Process?
No. A child process has its own Symfony Process timeout, which defaults to 60 seconds in the documented component behavior.
Should every PDF request use the same timeout?
No. HTML size, scripts, external assets, authentication, and renderer readiness can vary substantially. Use measured latency and a clear application deadline.
Why can a request still fail after increasing the timeout?
A proxy, queue worker, remote service, or renderer may have a shorter limit. The page may also be stalled on assets or an unsuitable network-idle condition.
When should I use an asynchronous job?
Use one when conversion can exceed an interactive request budget, when retries are required, or when a user does not need the PDF in the same HTTP response.


