加入收藏 | 设为首页 | 会员中心 | 我要投稿 济宁站长网 (https://www.0537zz.cn/)- 行业智能、边缘计算、专有云、AI硬件、5G!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php强制文件下载而非在浏览器打开的自定义函数分享

发布时间:2022-08-05 09:41:42 所属栏目:PHP教程 来源:互联网
导读:这篇文章主要介绍了php强制文件下载而非在浏览器打开的自定义函数分享,需要的朋友可以参考下。 有时我们希望如图片、文本文档、网页、mp3、pdf等内容,当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置header头信息。以下为一段不会产生乱
  这篇文章主要介绍了php强制文件下载而非在浏览器打开的自定义函数分享,需要的朋友可以参考下。
 
  有时我们希望如图片、文本文档、网页、mp3、pdf等内容,当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置header头信息。以下为一段不会产生乱码的php函数实现代码,其他程序语言也可参考之编写实现,代码如下:
 
  /**
   * Downloader
   *
   * @param $archivo
   *  path al archivo
   * @param $downloadfilename
   *  (null|string) el nombre que queres usar para el archivo que se va a descargar.
   *  (si no lo especificas usa el nombre actual del archivo)
   *
   * @return file stream
   */
  function download_file($archivo, $downloadfilename = null) {
      if (file_exists($archivo)) {
          $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
          header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename=' . $downloadfilename);
          header('Content-Transfer-Encoding: binary');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Pragma: public');
          header('Content-Length: ' . filesize($archivo));
   
          ob_clean();
          flush();
          readfile($archivo);
          exit;
      }
   
  }
   

(编辑:济宁站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读