php強製檔案下載的自訂函數程式碼

WBOY
發布: 2016-07-25 09:12:51
原創
896 人瀏覽過

有时希望当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置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. }
复制代码


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!