Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

The correct cookie method depends on what your PDF converter receives. If PHP has already authenticated the visitor and generated the permitted HTML, pass that HTML string to Dompdf or mPDF; the renderer does not need the browser’s session cookie. If a converter fetches a protected URL itself, that separate request must receive authentication, such as a cookie supplied with wkhtmltopdf’s --cookie option. Treat every session ID as a credential and never expose it unnecessarily.

First decide: HTML string or protected URL?

There are two different conversion flows, and confusing them causes most cookie problems.

Conversion input Where authentication happens Typical PHP approach
HTML already generated by your PHP application Your application starts the session, checks authorization, and builds the HTML before rendering. Dompdf loadHtml() or mPDF WriteHTML().
A URL fetched by the converter The converter makes a new HTTP request and must receive the required cookie or other authorization. wkhtmltopdf --cookie; optionally a protected cookie jar.
Local HTML file with protected remote assets Each remote image, stylesheet, or font request may need its own authorization. Configure the renderer’s cookie/header support and verify its resource-loading behavior.

A browser cookie is not automatically inherited by a PHP library or a separate command-line process. Select the path that matches your application before writing code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Securely create the authorized HTML in PHP

Start or resume the session before generating the document. PHP places request cookies in $_COOKIE, while the session subsystem validates the session according to your configured handler.

<?php
session_start();

if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Sign in required');
}

$reportOwner = (int) $_SESSION['user_id'];
$report = loadReportForUser($reportOwner); // Enforce authorization in the query/service.
if ($report === null) {
    http_response_code(404);
    exit('Report not found');
}

$html = renderReportTemplate($report); // Generate only data this user may see.

Do not put the session ID into the HTML, a PDF field, a URL, or application logs. PHP’s session guidance recommends cookie-based IDs, strict mode, and protections such as HttpOnly, Secure, and an appropriate SameSite value. A leaked session ID can grant access to resources associated with that session.

Set cookies before output

If your application must issue or change a cookie, call setcookie() before sending any body output, including whitespace or an HTML doctype.

<?php
setcookie('report_preference', 'compact', [
    'expires'  => time() + 3600,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

// Only after setcookie() and other headers:
echo 'Cookie instruction sent';

Render an authorized HTML string with Dompdf

Dompdf’s documented sequence is to load HTML, configure the paper, render, then stream or return the output. Because PHP has already applied access control, no browser cookie needs to be handed to Dompdf for the HTML itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
require __DIR__ . '/vendor/autoload.php';

use DompdfDompdf;
use DompdfOptions;

session_start();
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Sign in required');
}

$report = loadReportForUser((int) $_SESSION['user_id']);
if ($report === null) {
    http_response_code(404);
    exit('Report not found');
}

$html = renderReportTemplate($report);

$options = new Options();
$options->set('isRemoteEnabled', true); // Enable only when remote assets are trusted.
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('report.pdf', ['Attachment' => true]);

Enabling remote resources can cause additional HTTP requests. Those requests are not automatically authenticated merely because PHP’s session was authenticated. Prefer embedding permitted assets, using application-controlled URLs, or configuring resource authorization explicitly.

Render the same HTML with mPDF

mPDF accepts HTML through WriteHTML(). The authorization boundary remains in your application; sanitize and validate any user-controlled HTML before passing it to the renderer.

<?php
require __DIR__ . '/vendor/autoload.php';

use MpdfMpdf;

session_start();
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Sign in required');
}

$report = loadReportForUser((int) $_SESSION['user_id']);
if ($report === null) {
    http_response_code(404);
    exit('Report not found');
}

$html = renderReportTemplate($report);
$mpdf = new Mpdf(['format' => 'A4']);
$mpdf->WriteHTML($html);
$mpdf->Output('report.pdf', 'D');

The mPDF manual cautions that it is not intended to receive untrusted external HTML. Browser sanitization alone is not a sufficient security boundary for server-side PDF generation.

Give a URL renderer its own cookie

wkhtmltopdf makes a separate request to the target URL. Its documented --cookie <name> <value> option adds a cookie to that request, and --cookie-jar <path> reads and writes a cookie jar.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
wkhtmltopdf 
  --cookie PHPSESSID "$SESSION_ID" 
  https://example.invalid/private/report 
  report.pdf

This is an illustrative shell pattern, not a recommendation to place a live session ID in a shared process list. Use a protected execution environment, restrict permissions on any cookie jar, prevent command and web-server logs from recording the value, and prefer a short-lived, narrowly scoped token when your architecture supports one.

Why a browser cookie may still fail

  • The cookie’s domain or path does not match the URL requested by wkhtmltopdf.
  • The cookie is marked Secure but the renderer uses an HTTP URL.
  • The application redirects to another host that does not receive the cookie.
  • The page loads images, CSS, fonts, or API data from a different protected origin.
  • The session expires before the external process starts.
  • A security layer rejects the renderer’s user agent or blocks its network address.

Inspect the complete redirect chain and every protected resource. A successful top-level HTML request does not prove that its subresources were authorized.

Local files, queues, and background workers

Local HTML is not a browser session

Opening a local file gives the renderer no browser cookie. If the file references protected remote resources, those resource requests need suitable cookies or headers, and behavior differs by renderer and version. For predictable output, materialize authorized data and assets inside the worker’s controlled input instead of depending on a user’s browser session.

Asynchronous PDF jobs

In a queue, the original request’s cookie may no longer be available. Do not persist a long-lived session ID just to let a worker render a document. A safer design is to authorize the job immediately, store the narrowly scoped document data, or issue a short-lived worker token that cannot access unrelated user resources.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Security checklist

  • Authorize the user before selecting report data, not only before downloading the PDF.
  • Use HTTPS and configure Secure, HttpOnly, SameSite, and strict session handling as appropriate for your deployment.
  • Keep session IDs out of URLs, PDF content, source control, telemetry, shell history, and shared process listings.
  • Restrict cookie-jar file permissions and delete temporary jars after the conversion.
  • Sanitize untrusted HTML and constrain remote-resource access.
  • Use short-lived, least-privilege credentials for workers and external renderers.
  • Return generic errors to clients while keeping sensitive diagnostic details in protected logs.

Troubleshooting common failures

Symptom Likely cause Fix
PDF contains “sign in” page The renderer fetched a URL without the session cookie, or the cookie did not match the host/path. Pass the cookie with wkhtmltopdf, verify domain/path and redirects, or generate an authorized HTML string in PHP.
setcookie() has no effect Output was sent before the header. Move setcookie() before all output and check for accidental whitespace or an included file that prints.
HTML appears, but images or CSS are missing Remote subresources require separate authorization or are blocked by renderer policy. Embed or stage assets, authorize their requests, and check the renderer’s remote-resource settings.
Dompdf/mPDF output is unauthorized Untrusted HTML or data was passed without application-level filtering. Build HTML from authorized records, sanitize user content, and avoid allowing arbitrary markup or URLs.
Works interactively but fails in a queue The worker cannot use the original browser session or network context. Materialize the authorized document or issue a short-lived scoped worker credential.
Cookie appears in logs Debug logging, shell tracing, or process inspection exposed a credential. Redact values, disable tracing for the command, tighten process permissions, rotate the session, and invalidate the exposed credential.

Performance, reliability, and operational choices

Passing an already-authorized string avoids a second login/request path and gives your PHP code direct control over the data. URL-based conversion is useful when the page already exists as a carefully designed endpoint, but it adds network, redirect, cookie, and subresource failure modes. Neither the cited Dompdf, mPDF, nor wkhtmltopdf documentation establishes a universal speed or CSS-support ranking; verify the exact library and version used in your deployment.

For repeatable jobs, record the document ID, authorization decision, renderer version, input form, and non-secret failure reason. Set bounded timeouts, clean temporary files, and make retries safe so a retry cannot broaden the user’s access.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your requirement is simply to turn a public URL into a PDF or image, ScreenshotNeo makes one GET request and returns PNG, JPEG, WebP, or PDF. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. It also provides an MCP server for Claude, Cursor, and other MCP clients, with take_screenshot, get_page_info, and capture_pdf tools.

For a public page, the one-call examples are:

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 complete option and authentication details in the ScreenshotNeo documentation. Its 63 options include full-page capture with lazy images loaded, CSS-selector element capture, device presets and custom viewports, retina scale, PDF paper size/margins/landscape/page ranges, custom CSS and JavaScript, clicks, waits, ad/tracker/request blocking, headers and cookies, timezone and geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan, and yearly billing provides two months free. For protected application pages, use the service’s documented cookie or header options with a narrowly scoped credential rather than exposing a user’s long-lived session ID.

Create a free ScreenshotNeo account to get 1,000 screenshots a month without adding a card.

Frequently Asked Questions

Should I forward PHPSESSID when using Dompdf?

No. If PHP has already authorized the user and you pass the resulting HTML string to Dompdf, Dompdf does not need the browser session cookie. Forward credentials only when the renderer makes its own protected request.

Can a cookie authenticate images inside a PDF?

Only if the renderer sends suitable authorization on those image requests. A cookie on the top-level URL is not proof that cross-origin or separately fetched assets are authenticated.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What should a queued PDF job store?

Store the authorized document data or use a short-lived, narrowly scoped worker token. Avoid persisting a user’s long-lived browser session identifier.

The Bottom Line

Generate and authorize the HTML in PHP whenever possible, then pass the string to Dompdf or mPDF. If a separate renderer fetches a protected URL, provide authentication to that request with tightly controlled cookies or tokens.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.