Friday, 10 August 2018

Force File Download With PHP

When you supply files that web browsers can open they are usually opened inside the browser, rather than being downloaded. This can be annoying, especially where PDF documents are involved. You could supply the files in a compressed format in order to force users to download them, but this is also annoying as the user then has to uncompress the file.
You can force the web browser to supply the file as a download by using the header() function in PHP. The following little bit of code will take any filename and supply it as a download.
  1. <?php
  2. $file = $_GET['file'];
  3. header('Content-type: octet/stream');
  4. header('Content-disposition: attachment; filename='.$file.';');
  5. header('Content-Length: '.filesize($file));
  6. readfile($file);
  7. ?>
All you have to do is link to this script with the argument being the file name you want your users to be able to download.
<a href="force.php?file=hashbangcode-image.png" title="Download">PNG Image</a>
The benefit of doing things this way means that you can also put some tracking elements into the start of the file to record what and when the file was downloaded.
However, be very careful here. In it's current state the script will allow users to download ANY file within the directory you have the script in, just by supplying the name. This is a big security feature as a use could get hold of your database password file quite easily. To get around this you can restrict the file type to either jpg, gif, png or pdf by using the following code.
  1. <?php
  2. $file = $_GET['file'];
  3. $ext = substr($file,-3);
  4. if($ext=='jpg' || $ext=='gif' || $ext=='png' || $ext=='pdf'){
  5. header('Content-type: octet/stream');
  6. header('Content-disposition: attachment; filename='.$file.';');
  7. header('Content-Length: '.filesize($file));
  8. readfile($file);
  9. }
  10. ?>
Finally, it is best to check to see if the file exists before trying to get users to download it. It is doesn't then they will get a file full off PHP error codes.

0 comments:

Post a Comment