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:
download image
Then in the file download.php, the important code will be:
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 |
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.