Home >Backend Development >PHP Tutorial >Custom function code for php to force file download

Custom function code for php to force file download

WBOY
WBOYOriginal
2016-07-25 09:12:51965browse

Sometimes you want to download directly when clicking the corresponding link instead of displaying it on the web page, then you need to forcefully set the header information.

Share a piece of PHP function implementation code that does not produce garbled characters to achieve forced downloading of files.

Example, PHP code to implement forced downloading of files.

  1. /**
  2. * Downloader
  3. *
  4. * @param $file
  5. * path to the file
  6. * @param $downloadfilename
  7. * (null|string) the name you want to use for the file to be downloaded.
  8. * (if you don't specify it use current file name)
  9. *
  10. * @return file stream
  11. */ bbs.it-home.org
  12. function download_file($archivo, $downloadfilename = null) {
  13. if (file_exists($archivo)) {
  14. $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
  15. header('Content-Description: File Transfer');
  16. header('Content-Type: application/octet-stream');
  17. header ('Content-Disposition: attachment; filename=' . $downloadfilename);
  18. header('Content-Transfer-Encoding: binary');
  19. header('Expires: 0');
  20. header('Cache-Control: must- revalidate, post-check=0, pre-check=0');
  21. header('Pragma: public');
  22. header('Content-Length: ' . filesize($archivo));
  23. ob_clean();
  24. flush ();
  25. readfile($archivo);
  26. exit;
  27. }
  28. }
Copy code


Statement:
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