How to prompt user to download a file in browser from custom module php code?

I tried first the php way

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');

It silently fails. Then I realized there is a "drupal way" to do it. So I tried

drupal_add_http_header('Content-Type', 'application/octet-stream');
drupal_add_http_header('Content-disposition', 'attachment; filename='.$fname);
drupal_add_http_header('Content-Length', filesize($fpath));

but still not working. I think one possible reason for failure is that I am not sure at each step which is the correct path I should use.

Should it be '/home/mysite/public_html/sites/default/files/pdfs/'.$filename.'.pdf'

or just the part that starts in the drupal root '/sites/default/files/pdfs/'.$filename.'.pdf'

or even just 'public://pdfs/'.$filename.'.pdf'

as I see it in some other threads. I wonder why it has to be so complicated.

3 Answers 3


Have you tried the http://drupal.org/project/file_force Module ?

Some details from the module's project page:

File Force Download can be used to force the user's web browser to download the file to disk instead of displaying it in the browser window.

Web browsers today are pre-configured to render various types of media directly, such as text files, various image, video and audio formats, PDF documents, and Flash movies. While it is still possible to save such files afterwards by right-clicking on them and selecting "Save As..", it is sometimes desirable to just offer the file for download in the first place. File Force Download solves this issue by supplying a file with certain HTTP headers which instruct the web browser to download the file to the user's disk instead of displaying it in a browser window.

It should be a good starting point for inspiration for your own module.

  • Thanks for the idea. I'll try that. Poaching other modules' code is the way to go!
    – Mister
    Commented Sep 8, 2012 at 13:33

drupal_realpath() will give you the absolute path to the file on your server, however, the recommended way is to use file_create_url() to generate the URL to the file, which also sets you up for CDN integration.


There is a function called file_transfer() that will take a URI (like public://pdfs/myfile.pdf) and the HTTP headers in an array, see


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.