Why Your PHP File Download Headers Aren't Triggering a Save Dialog
You've verified that your headers are being sent correctly. You see Content-Disposition: attachment; filename="Image.png" in the network tab of your browser. Yet, instead of opening the browser's native "Save As" dialog immediately, the file either opens inline or the browser hangs waiting for more data before finally prompting you to save it. This frustration is common because many online tutorials list headers that are technically correct but incomplete regarding how modern browsers handle streaming responses.
The core issue usually isn't the Content-Disposition header itself; it's the order of operations and how PHP handles output buffering relative to those headers. Browsers expect a specific state before they commit to downloading a file versus displaying one. If any byte is sent to the output buffer before the headers are finalized, the browser assumes the content should be rendered inline, regardless of what your Content-Disposition says.
Consider this snippet often found in tutorials:
<?php
$size = filesize("Image.png");
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile("Image.png");
While this code sets the headers correctly, it assumes that readfile() will flush immediately without interference. In a standard PHP environment with output buffering enabled (which is default in most configurations), PHP buffers the output until it hits a certain threshold or hits an explicit flush. If the user's browser starts rendering the image before the download dialog appears, you've lost control of the disposition.
The critical missing piece in many "basic" examples is ensuring that no other output is sent at all before the headers, and explicitly disabling output buffering for this specific request. Even a stray newline or BOM at the top of your file can break the header block. The most robust approach involves turning off output buffering immediately after sending headers to ensure the stream is treated as raw binary data:
<?php
// Ensure no previous output has been sent
if (ob_get_level()) {
ob_clean();
}
$filename = "Image.png";
$content_type = "image/png"; // Adjust based on actual file type
header('Content-Type: ' . $content_type);
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache'); // Legacy support for older browsers
// Disable output buffering to force immediate stream handling
ob_end_clean();
readfile($filename);
exit;
The decision to use attachment is intentional here. While inline tells the browser "show this," attachment explicitly instructs it to treat the resource as a file to be stored locally. However, some browsers are stubborn and will attempt to inline render images regardless of headers if they believe the content type is safe to view. This is why specifying the exact MIME type (image/png) is crucial; using application/octet-stream forces the download but results in no preview for supported types.
A common pitfall developers encounter involves URL encoding. If your filename contains spaces or special characters, you must encode them before sending them in the header. Sending a raw string like filename="My Report.pdf" when the actual file is My Report.pdf often leads to security warnings or failure to download in strict browsers. Always use urlencode() on the filename parameter within the Content-Disposition header:
header('Content-Disposition: attachment; filename="' . urlencode($filename) . '"');
Another subtle issue arises when mixing this logic into larger applications. If your script is part of a route that might return JSON or HTML under certain conditions, you must ensure the download logic runs in isolation. In frameworks like Laravel, you might need to explicitly clear the output buffer before invoking readfile() to prevent cached responses from interfering with the stream.
For production environments where security and file handling are paramount, relying on raw readfile() can be risky if the file path isn't strictly validated against a whitelist. Always ensure the filename matches the actual file on disk exactly, preventing directory traversal attacks or serving unintended files.
