Приглашаем посетить
Спорт (sport.niv.ru)

Returning Files with an HTTP Request

Previous
Table of Contents
Next

Returning Files with an HTTP Request

$filename = 'httpfile.zip';
header("Content-Disposition: attachment; filename =
$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 6.6 shows its result in the browser.

Sending a File with HTTP (httpfile.php)
<?php
  $filename = 'httpfile.zip';
  $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;
?>

Figure 6.6. The browser wants to save the file.

Returning Files with an HTTP Request


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



Previous
Table of Contents
Next