Posted By

MMDeveloper on 10/01/08


Tagged

php file download force


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

Scooter
luman
ilumin
muoto
esundahl
fana


Universal Force File Download


 / Published in: PHP
 

URL: http://www.mechanicmatt.com/

so lets say you saved this script in your document root as "dlFile.php". so it's located at yourdomain.com/dlFile.php

and your files are located at yourdomain.com/files/

then you would link to it like this

href="dlFile.php?filename=podcast1.mp3". If your file is in a subdirectory of /files/ then you'd use

dlFile.php?filename=subDir/filename.jpg

Refer to the comment in the php script to specify the path where the files are stored.

  1. <?php
  2. if ($_REQUEST["filename"] != "") {
  3. $filename = str_replace("../", "", $_REQUEST["filename"]);
  4. if ($filename != "") {
  5.  
  6. /*
  7.   this is where you set the base path and the file for security reasons.
  8.   If you wish to manually hard code a base path, then comment out the following line,
  9.   and use the line after it
  10.   */
  11. $file = dirname(__FILE__) . "/files/" . $filename;
  12.  
  13. //$file = "/var/www/htdocs/audio/" . $filename;
  14.  
  15.  
  16. if (file_exists($file)) {
  17. header ("Content-type: octet/stream");
  18. header ("Content-disposition: attachment; filename=" . str_replace(" ", "_", basename($file)) . ";");
  19. header ("Content-Length: " . filesize($file));
  20. readfile($file);
  21. die();
  22. }
  23. else {
  24. echo '
  25. <script type="text/javascript">
  26. <!--
  27. alert("' . $file . '\n\nI do not currently have this image ready for download");
  28. -->
  29. </script>
  30. ';
  31. }
  32. } else {}
  33. } else {}
  34. ?>

Report this snippet  

You need to login to post a comment.