Friday, December 7, 2007

PHP force file download

How to force file download in PHP



Here is how you can force a client to download a file.

$text = 'force me to download';

header("Content-Length: " . strlen($text) );
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=downloadme.txt');

This will force browser to download/save the file named 'downloadme.txt'

You you want to download other types of files here is a small list of types of files that you can use in Content-Type field:

  • "pdf": "application/pdf"
  • "exe": "application/octet-stream"
  • "zip": "application/zip"
  • "xls": "application/vnd.ms-excel"
  • "ppt": "application/vnd.ms-powerpoint"
  • "gif": "image/gif"
  • "png": "image/png"
  • "jpg": "image/jpg"