Using header() to change filename in URL?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hello -

I have a php script which return a pdf to the browser. Everything
works okay, but if you try to save the pdf the filename is
report.php . I'd like to get it so that I can dynamically rename it in
the php script itself -- e.g. "July Report.pdf" or something like

I was looking at header() and there is a filename= option, but it
seems like that's only for file downloads. Is there a way to get this
to still open in the browser, and rename the file?

Re: Using header() to change filename in URL?

Quoted text here. Click to load it

# MIME type:
$file_mime = "application/pdf";

# Suggested file name for the remote client.
# In this example only ASCII printable chars allowed, with the exception
# of \ and ". For extended charsets, for example UTF-8, see
$file_name = "suggested_file_name.pdf";

# Local path of the actual file to be sent:
$file_path = "/actual/file/name.dat";

header("Content-Type: $file_mime");
header("Content-Disposition: attachment; filename=\"$file_name\"");
# Optional content lenght:
header("Content-Length: " . filesize($file_path));

/_|_\  Umberto Salsi

Re: Using header() to change filename in URL?

On Thu, 3 Sep 2009 13:20:53 -0700 (PDT), lawpoop wrote:
Quoted text here. Click to load it

From an program where I'm sending XML disguised as an Excel spreadsheet:

header('Content-Type: application/');
header('Content-disposition: filename=mpt_summary.xls');

You'll (obviously) want something more like

header('Content-Type: application/pdf');
header('Content-disposition: filename="July Report.pdf"');

What the browser does with the file that comes in is up to the browser,
but it will generally either open the doc in the browser, safe the file
under the suggested name, or prompt the user for which to do. What it
generally WON'T do is try to use the script name anymore.

8. After I kidnap the beautiful princess, we will be married immediately in a
   quiet civil ceremony, not a lavish spectacle in three weeks' time during
   which the final phase of my plan will be carried out.
                --Peter Anspach's list of things to do as an Evil Overlord

Re: Using header() to change filename in URL?


Quoted text here. Click to load it

If you want that filename on the client side, you should use a URL which
contains it, e.g.

To make handling a bit easier, you could use Apaches mod_rewrite to
rewrite the above URL internally to something like this:

Then your script just has to check the 'file' parameter and deliver the
requested report with an appropriate Content-Type header. You might also
add the Content-Disposition header as suggested earlier.


Site Timeline