PHP code to force download of specified type of file

WBOY
Release: 2016-07-25 09:00:35
Original
904 people have browsed it
  1. //Prompt download
  2. //site http://bbs.it-home.org
  3. function downloadFile($file){
  4. /*Coded by Alessio Delmonti*/
  5. $file_name = $file;
  6. $mime = 'application/force-download';
  7. header('Pragma: public'); // required
  8. header('Expires: 0'); // no cache
  9. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  10. header('Cache-Control: private',false);
  11. header('Content-Type: '.$mime);
  12. header(' Content-Disposition: attachment; filename="'.basename($file_name).'"');
  13. header('Content-Transfer-Encoding: binary');
  14. header('Connection: close');
  15. readfile($ file_name); // push it out
  16. exit();
  17. }
  18. ?>
Copy code

php will download the file instead of downloading the hyperlink, which can reduce hotlinking! Give the file to the browser and let the browser download it.

Take txt type as an example

To avoid opening the txt file directly in the browser, you can rename the txt file to a file that the browser does not recognize (such as rar). In this case, because the browser cannot recognize the rar type file, the user can only download it. The above methods are sometimes very inapplicable.

We use another method to set the format of the document through the header information of the php file to achieve the purpose of click download. Example:

  1. //php header function forces downloading
  2. // site bbs.it-home.org
  3. $filename = '/path/'.$_GET['file'].'. txt'; //File path
  4. header("Content-Type: application/force-download");
  5. header("Content-Disposition: attachment; filename=".basename($filename));
  6. readfile($filename) ;
  7. ?>
Copy code

Instructions: The first header function sets the value of Content-Type to application/force-download; The second header function sets the file to be downloaded. Note that filename here is a file name that does not include a path. The value of filename will be the file name in the dialog box that pops up after clicking download. If there is a path, the file name in the dialog box that pops up is unknown; Finally, through the readfile function, the file stream is output to the browser to realize the download of the txt file.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!