Force download with PHP and mime types

This is a basic feature post, but I wrote it to keep it handy.

If you need to link a document/picture/video or whatever file in your website, you can do it using an a-tag <a href…> link </a> , but what if you want to force this file to be download by the user instead of be opened by the browser?

To do that, you’ll need to write a bridge script between the page and the file, and then the link as it follows:

<a href='download.php?file=filename.jpg'>download image</a>

Then in the file download.php, the important code will be:

<?php
// .... before that, you should, well
// must check the file, the path,
// code injection...
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=name_of_the_file_to_show.jpg"');
readfile("path/to/".$_GET["file"]);
?>

 

You can change the content-type to help browser identifying the file type. Below I attach a list of the most common/used:

 

Extension Type
(all files) application/octet-stream
avi video/x-msvideo
bmp image/bmp
css text/css
doc application/msword
dot application/msword
eps application/postscript
gif image/gif
gtar application/x-gtar
gz application/x-gzip
htm text/html
html text/html
ico image/x-icon
jpe image/jpeg
jpeg image/jpeg
jpg image/jpeg
js application/x-javascript
latex application/x-latex
mov video/quicktime
mp2 video/mpeg
mp3 audio/mpeg
mpa video/mpeg
mpe video/mpeg
mpeg video/mpeg
mpg video/mpeg
pdf application/pdf
pps application/vnd.ms-powerpoint
ppt application/vnd.ms-powerpoint
prf application/pics-rules
ps application/postscript
qt video/quicktime
rtf application/rtf
svg image/svg+xml
swf application/x-shockwave-flash
tgz application/x-compressed
tif image/tiff
tiff image/tiff
txt text/plain
xls application/vnd.ms-excel
zip application/zip

 

Another way would be using fileinfo or other functions available in php to query a file.

Read More