Using Header() To Rename PDFs in a Download Link
When building a script that generates PDF reports, the default behavior of PHP is to name the downloaded file after the executing script. If your entry point is report_pdf.php, Acrobat and other viewers will suggest saving it as report_pdf. While functional, this makes manual archiving tedious; you end up renaming every single file or creating a subfolder structure just to keep things organized.
The standard approach to solving this is modifying the HTTP headers before sending any output. The specific header required is Content-Disposition, which tells the browser how to handle the response and what name to assign the payload. However, implementation details regarding character encoding and disposition types often lead to unexpected behavior where the filename remains unchanged or the browser ignores the instruction entirely.
The Critical Role of Charset
The primary reason the code snippet provided in many forumsâheader('Content-disposition: filename="July Report.pdf"');âfails is not a lack of knowledge about the header syntax, but rather a missing directive regarding character encoding. Modern web browsers and PDF viewers expect UTF-8 encoded headers for non-ASCII characters to render filenames correctly. If your filename contains spaces or special characters, and you do not explicitly define the charset, the browser may interpret the bytes incorrectly based on its default locale settings.
To ensure compatibility across different clients, you must send the Content-Type header with the UTF-8 parameter before setting the disposition header. Without this, the browser might strip the filename or display it with garbled characters depending on the operating system's locale.
header('Content-Type: application/pdf; charset=utf-8');
header('Content-Disposition: inline; filename="July Report.pdf"');
Note that while inline suggests the file can be viewed in the browser and attachment forces a download, both allow you to specify a custom filename. The choice between them depends on your user experience goals. For reports that users intend to save immediately, attachment is generally preferred because it prompts the "Save As" dialog or downloads the file directly without opening it first.
Implementation and Output Control
The code structure provided in the source material using classes like Cpdf demonstrates a classic pattern: generate the PDF object in memory and stream it directly to the output buffer. This is efficient and avoids writing temporary files to the disk, which simplifies cleanup but introduces strict requirements for header ordering.
Crucially, no HTML or whitespace can exist before these headers are sent. If your script includes a shebang line, debug statements, or even accidental newlines in the source file before the <?php tag closes, Apache will return a 500 Internal Server Error because it interprets the output as text rather than a header block.
Once the headers are set and the PDF object is streamed via $pdf->stream(), the script must terminate immediately. Using exit; ensures that no subsequent code attempts to send additional headers or output data, which would corrupt the response stream.
<?php
// Ensure no whitespace before this line
header('Content-Type: application/pdf; charset=utf-8');
header('Content-Disposition: attachment; filename="July Report.pdf"');
require_once('class.ezpdf.php');
require_once('class.pdf.php');
$pdf = new Cpdf();
$pdf->selectFont('./fonts/Helvetica');
$pdf->addText(30, 400, 30, 'Hello World');
$pdf->stream();
exit;
Handling Dynamic Filenames
If you wish to dynamically generate the filename based on variables like $date or $user_id, simply concatenate the string into the header. However, be wary of special characters that might break the header format. For instance, filenames containing quotes or backslashes need escaping. It is often safer to use basename() to derive a clean filename from a path variable if you are constructing paths dynamically.
$filename = basename($reportPath) . '_generated.pdf';
$filename = str_replace(['"', "'", "\\", "<", ">", "|", "?"], '', $filename); // Basic sanitization
header('Content-Disposition: attachment; filename="' . $filename . '"');
While mod_rewrite can alter the URL path, it does not influence the actual file name suggested by the browser for the downloaded content. The Content-Disposition header is the authoritative source for the download filename, regardless of what the URL points to. This separation allows you to keep your URLs clean and SEO-friendly while presenting a user-friendly filename in the save dialog.
For developers working within the Laravel ecosystem, similar logic applies when streaming responses from controllers using the Response facade or $response->download() method, where the second argument handles the filename directly.