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

yipeiwu_com5年前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");
 header( "Content-type:  application/octet-stream "); 
 header( "Accept-Ranges:  bytes "); 
 header( "Content-Disposition:  attachment;  filename= {$date}.doc"); 
 $size=readfile($filename); 
  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中数值计算的注意事项

一:四舍五入 1.round — 对浮点数进行四舍五入 float round ( float $val [, int $precision ] ) 2:floor — 舍去法取...

php实现无限级分类实现代码(递归方法)

开始以为这样的功能似乎很难,之前也做过一个百科的东西,其中也涉及到了分类的功能,不过不是无限级的分类,而是简单的实现了固定的三级分类,当时是自己设计的,想在想起来实现方法太土了,其实三级...

解析php根据ip查询所在地区(非常有用,赶集网就用到)

dat文件,关于ip对应地区的信息文件qqwry.dat文件网上自己下载class类文件,解析qqwry.data文件的IpLocation.php文件复制代码 代码如下:<?ph...

PHP的pcntl多进程用法实例

本文实例讲述了PHP的pcntl多进程用法。分享给大家供大家参考。具体分析如下: PHP使用PCNTL系列的函数也能做到多进程处理一个事务。比如我需要从数据库中获取80w条的数据,再做一...

微信JSSDK分享功能图文实例详解

微信JSSDK分享功能图文实例详解

本文实例讲述了微信JSSDK分享功能。分享给大家供大家参考,具体如下: 这里以微信分享到朋友圈,分享给微信好友为例为参考,进行调用测试,想添加其他的功能,自行查看开发人员文档即可 工欲...