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:
Another way would be using fileinfo or other functions available in php to query a file.