PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

Content-Disposition: - Sending Files for Downloading

This section provides a tutorial example on how to insert the 'Content-Disposition:' header line in a HTTP response to tell the browser to prompt the user the download and save the response entity body as a file.

In the previous section, the requested file is delivered to the browser for opening immediately. HTTP does also support another header line called "Content-Disposition" which tells the browser to not open the file immediately, but prepare for downloading the entity body. The following script will show you how to do this:

<?php #GetFile.php
# Copyright (c) 2005 by Dr. Herong Yang, http://www.herongyang.com/
#
   $ok = array_key_exists('QUERY_STRING', $_SERVER);
   if ($ok) {
      $p = $_SERVER['QUERY_STRING'];
      $ok = strlen($p)>0 && file_exists($p);
   }
   if ($ok) {
      if (strpos($p,".html")!=false) {
         header("Content-Type: text/html");
      } else if (strpos($p,".gif")!=false) {
         header("Content-Type: image/gif");
      } else if (strpos($p,".pdf")!=false) {
         header("Content-Type: application/pdf");
      } else if (strpos($p,".doc")!=false) {
         header("Content-Type: application/msword");
      } else {
         $ok = false;
      }
   }
   if ($ok) {
      header("Content-Length: ".filesize($p));
      header("Content-disposition: attachment; filename=".$p);
      readfile($p);
   } else {
      print("<html><body>Bad request.</body></html>");
   }
?>

In this page, anther header line, "Content-Disposition", is added to the response, in which I am telling the client program that the entity data is an attachment, with file name specified.

Now try to use IE to request http://localhost/Download.php?hello.pdf, you will see IE prompting you to save the attachment instead of calling Adobe Reader to display the data.

Try to use IE to request http://localhost/Download.php?other_existing_file, you will see IE prompting you to save the attachment. The script is working correctly.

Last update: 2005.

Sections in This Chapter

What Is an HTTP Response?

HTTP Response Header Lines

header() - Inserting a Raw Header Lines

HttpRequestGet.php - Viewing Header Lines

Response Header Lines of Static Files

HttpHeaderLines.php - Examples of Inserting Header Lines

Location: - Forcing the Browser to Redirect to Another URL

Content-Type: - Generating Non-HTML Response Body

Content-Disposition: - Sending Files for Downloading

Dr. Herong Yang, updated in 2009
Content-Disposition: - Sending Files for Downloading