首页 >后端开发 >PHP问题 > 正文

php怎么实现保存下载文件

原创2021-07-14 09:13:020725

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

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

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

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

第一种:

<?php 
function downfile()
{
 $filename=realpath("resume.html"); //文件名
 $date=date("Ymd-H:i:m");
 Header( "Content-type:  application/octet-stream "); 
 Header( "Accept-Ranges:  bytes "); 
Header( "Accept-Length: " .filesize($filename));
 header( "Content-Disposition:  attachment;  filename= {$date}.doc"); 
 echo file_get_contents($filename);
 readfile($filename); 
}
downfile();
?>

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

<?php 
function downfile($fileurl)
{
 ob_start(); 
 $filename=$fileurl;
 $date=date("Ymd-H:i:m");
 $size=readfile($filename);
 header( "Content-type:  application/octet-stream "); 
 header( "Accept-Ranges:  bytes "); 
 header( "Content-Disposition:  attachment;  filename= {$date}.doc"); 
 header( "Accept-Length: " .$size);
}
 $url="url地址";
 downfile($url);
?>

第二种:

<?php 
function downfile($fileurl)
{
$filename=$fileurl;
$file  =  fopen($filename, "rb"); 
Header( "Content-type:  application/octet-stream "); 
Header( "Accept-Ranges:  bytes "); 
Header( "Content-Disposition:  attachment;  filename= 4.doc"); 
$contents = "";
while (!feof($file)) {
 $contents .= fread($file, 8192);
}
echo $contents;
fclose($file); 
}
$url="url地址";
downfile($url);
?>

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

方法一:

<?php
/**
* 下载文件
* header函数
*
*/
header('Content-Description: File Transfer');
 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
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($filepath));
readfile($file_path);
?>

了解php中header函数的用法。

方法二:

<?php
//文件下载
//readfile
$fileinfo = pathinfo($filename);
header('Content-type: application/x-'.$fileinfo['extension']);
header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
header('Content-Length: '.filesize($filename));
readfile($thefile);
exit();
?>

推荐学习:《PHP视频教程

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

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:php
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    推荐视频教程
  • 细说PHP(2021版)第一季细说PHP(2021版)第一季
  • 细说PHP(2021版)第二季细说PHP(2021版)第二季
  • 细说PHP(2021版)第三季细说PHP(2021版)第三季
  • 细说PHP(2021版)第四季细说PHP(2021版)第四季
  • php求职面试之道【公益直播】php求职面试之道【公益直播】
  • 视频教程分类