当前位置:Gxlcms > PHP教程 > php怎么实现保存下载文件

php怎么实现保存下载文件

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

php实现保存下载文件的方法:1、通过“function downfile(){...}”方法实现下载文件;2、通过header函数实现保存下载。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php 下载保存文件保存到本地的两种实现方法

这里的下载,指的是 弹出下载提示框。

第一种:

  1. <?php
  2. function downfile()
  3. {
  4. $filename=realpath("resume.html"); //文件名
  5. $date=date("Ymd-H:i:m");
  6. Header( "Content-type: application/octet-stream ");
  7. Header( "Accept-Ranges: bytes ");
  8. Header( "Accept-Length: " .filesize($filename));
  9. header( "Content-Disposition: attachment; filename= {$date}.doc");
  10. echo file_get_contents($filename);
  11. readfile($filename);
  12. }
  13. downfile();
  14. ?>

或 (推荐这种方法,亲测可行,其他的没测试)

  1. <?php
  2. function downfile($fileurl)
  3. {
  4. ob_start();
  5. $filename=$fileurl;
  6. $date=date("Ymd-H:i:m");
  7. $size=readfile($filename);
  8. header( "Content-type: application/octet-stream ");
  9. header( "Accept-Ranges: bytes ");
  10. header( "Content-Disposition: attachment; filename= {$date}.doc");
  11. header( "Accept-Length: " .$size);
  12. }
  13. $url="url地址";
  14. downfile($url);
  15. ?>

第二种:

  1. <?php
  2. function downfile($fileurl)
  3. {
  4. $filename=$fileurl;
  5. $file = fopen($filename, "rb");
  6. Header( "Content-type: application/octet-stream ");
  7. Header( "Accept-Ranges: bytes ");
  8. Header( "Content-Disposition: attachment; filename= 4.doc");
  9. $contents = "";
  10. while (!feof($file)) {
  11. $contents .= fread($file, 8192);
  12. }
  13. echo $contents;
  14. fclose($file);
  15. }
  16. $url="url地址";
  17. downfile($url);
  18. ?>

PHP实现下载文件的两种方法。分享下,有用到的朋友看看哦。

方法一:

  1. <?php
  2. /**
  3. * 下载文件
  4. * header函数
  5. *
  6. */
  7. header('Content-Description: File Transfer');
  8. header('Content-Type: application/octet-stream');
  9. header('Content-Disposition: attachment; filename='.basename($filepath));
  10. header('Content-Transfer-Encoding: binary');
  11. header('Expires: 0′);
  12. header('Cache-Control: must-revalidate, post-check=0, pre-check=0′);
  13. header('Pragma: public');
  14. header('Content-Length: ' . filesize($filepath));
  15. readfile($file_path);
  16. ?>

了解php中header函数的用法。

方法二:

  1. <?php
  2. //文件下载
  3. //readfile
  4. $fileinfo = pathinfo($filename);
  5. header('Content-type: application/x-'.$fileinfo['extension']);
  6. header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
  7. header('Content-Length: '.filesize($filename));
  8. readfile($thefile);
  9. exit();
  10. ?>

推荐学习:《PHP视频教程》

以上就是php怎么实现保存下载文件的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行