PHP: File Downloads HTTP Headers
Pete
In PHP you can provide file downloads by using a PHP page to “pass through” the file. Of course you could just link to the actual file, however this technique means your file can kept outside of your website root. Another advantage is you can integrate this system into a PHP based user/password system easily.
Now this technique is fairly straightforward, but you need to make sure you get the HTTP Headers correct for it to run smoothly. Here’s the code:
-
$file = "/path/to/file.txt";
-
-
//This will set the Content-Type to the appropriate setting for the file
-
switch ($file_extension)
-
{
-
case "htm":
-
case "xhtml";
-
case "txt";
-
case "html": $ctype="text/html"; break;
-
case "pdf": $ctype="application/pdf"; break;
-
case "doc": $ctype="application/msword"; break;
-
case "exe": $ctype="application/octet-stream"; break;
-
case "zip": $ctype="application/zip"; break;
-
case "xls": $ctype="application/vnd.ms-excel"; break;
-
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
-
case "gif": $ctype="image/gif"; break;
-
case "png": $ctype="image/png"; break;
-
case "jpeg":
-
case "jpg": $ctype="image/jpeg"; break;
-
case "mp3": $ctype="audio/mpeg"; break;
-
case "wav": $ctype="audio/x-wav"; break;
-
case "mpeg":
-
case "mpg":
-
case "mpe": $ctype="video/mpeg"; break;
-
case "mov": $ctype="video/quicktime"; break;
-
case "avi": $ctype="video/x-msvideo"; break;
-
default: $ctype="application/force-download";
-
}
-
-
//Begin writing headers
-
//Use the switch-generated Content-Type
-
-
// regex stops download prompt for browser associated types
-
-
// output the file
I will be writing a follow up article in the future that shows how this technique can be improvement using Apache's mod-rewrite to provide cleaner URLs for file downloads.
Note: The regular expression on line 42 will make files normally associated with the browser (images, webpages, etc) open inside the browser. If you want to get the “open/save” download prompt for all types of files then comment out this line.
Note: Make sure you use: “Content-Type: image/jpeg” for JPGs, IE doesn’t seems to like “Content-Type: image/jpg”
# Pete Graham
Posted in Website Development, php, programming, regular expressions |
1 Comment »