Logo Background RSS

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

    Bookmark and share:
    • del.icio.us
    • Digg
    • StumbleUpon
    • BlinkList
    • blogmarks
    • Furl
    • Slashdot
    • Spurl
    • Technorati
    • YahooMyWeb
    • description
    • Facebook
    • Google
    • Live
    • Ma.gnolia
    • NewsVine
    • Reddit
    • TwitThis

Advertisement

  1. #1 Jon B
    September 18th, 2006 at 10:57 pm

    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!

    Post ReplyPost Reply
  2. #2 vinu
    September 19th, 2006 at 7:01 pm

    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”);

    Post ReplyPost Reply
Leave a Comment