PHP Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.21

Controlling HTTP Response Header Lines

Part:   1  2  3  4  5  6  7 

PHP Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Non ASCII Characters with MySQL

Inputting Non ASCII Characters

Controlling Response Header Lines

HTTP Request Variables

Sessions

Using Cookies

PHP SOAP Extension

PHP SOAP Extension - Server

Directories, Files and Images

Using MySQL with PHP

... Table of Contents

(Continued from previous part...)

Sending Files for Downloading

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.

Conclusions

  • Setting header lines in PHP is simple, one function, header(), all cases.
  • "Location" is a interesting header line. It tells the browser to redirect itself to a new URL.
  • "Content-disposition" tells the browser to prepare for downloading the entity body.
  • I like the powerful function, readfile(), reading the content of a file and sending it to the HTTP response directly.

Part:   1  2  3  4  5  6  7 

Dr. Herong Yang, updated in 2006
PHP Tutorials - Herong's Tutorial Notes - Controlling HTTP Response Header Lines