当前位置:Gxlcms > PHP教程 > php强制文件下载的自定义函数代码

php强制文件下载的自定义函数代码

时间:2021-07-01 10:21:17 帮助过:19人阅读

有时希望当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置header头信息。

分享一段不会产生乱码的php函数实现代码,实现文件的强制下载。

例子,php实现文件强制下载的代码。

  1. /**
  2. * Downloader
  3. *
  4. * @param $archivo
  5. * path al archivo
  6. * @param $downloadfilename
  7. * (null|string) el nombre que queres usar para el archivo que se va a descargar.
  8. * (si no lo especificas usa el nombre actual del archivo)
  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. }

人气教程排行