Returning Files with an HTTP Request

$filename = '';
header("Content-Disposition: attachment; filename =

When a PHP script shall return a (downloadable) file instead of HTML, the correct HTTP headers have to be sent:

  • Content-Disposition for the (proposed) name of the file

  • Content-Length for the file size

  • Content-Type for the MIME type of the file

The preceding code reads in a ZIP file and sends it to the client; figure shows its result in the browser.

Sending a File with HTTP

  $filename = '';
  $mimetype = 'application/zip';
  $data = file_get_contents($filename);
  $size = strlen($data);
  header("Content-Disposition: attachment; filename
    = $filename");
  header("Content-Length: $size");
  header("Content-Type: $mimetype");
  echo $data;

The browser wants to save the file.

What Does PEAR Offer?

The following PEAR packages offer functionality that can be used for working with files and streams:

  • File offers some helper functions for file access, some of the deprecated to new functionality in more recent PHP releases

  • File_Find searches a path for certain files or patterns

  • File_SearchReplace does a Search and Replace within files

  • Stream_Var allows you to save variables in streams, so you can access them like you would access files or streams