VT’s Tech Blog RSS

Advertisement

Force a download on the browser

  • Here’s a piece of code which will force download a pdf instead of showing it inline in the browser.
    < ?php
    header('Pragma: public');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: none');
    header('Content-Type: application/pdf; name="$path->pdfname"');
    header('Content-Disposition: inline; filename="$path->pdfname"');
    readfile($path->pdfpath);
    ?>

    This code can be modifed to allow other file formats to be downloaded by just changing the mime type in the Content-Type: tag to the correct type for the file you wish to send.

    Here’s a quick reference to frequently used mime-types:

    http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html

    • Share/Save/Bookmark

Advertisement

  • Jon B
    Can you give an example of how this is used, using actual filenames? I'm unclear on how $path->pdfname and $path->pdfpath would be written in actual use. Thanks!
  • Jon,

    Here's a simple example which throws a csv file for download:

    header('Pragma: public');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: none');
    header('Content-Type: application/excel; name="mycsvdownload.csv"');
    header('Content-Disposition: attachment; filename="mycsvdownload.csv"');
    print ("Name, Email, Location\\n");
    print ("Vinu, me@xyz.com, Bangalore\\n");
blog comments powered by Disqus