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

yipeiwu_com6年前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下防止单引号,双引号在接受页面转义的设置方法

PHP页面中如果不希望出现以下情况: 单引号被转义为 \' 双引号被转义为 \" 那么可以进行如下设置以防止: 方法一:在PHP.ini中设置:magic_quotes_gpc = Of...

thinkphp框架下404页面设置 仅三步

404页面即系统在找不到请求的操作方法和找不到请求的控制器名称时的一种报错行为的优化。 在很多网站中都会有使用404页面的时候,在ThinkPHP框架中该如何设置呢,接下来我介绍其中一种...

不用mod_rewrite直接用php实现伪静态化页面代码

在你的程序初始化时使用如下代码: 复制代码 代码如下:<?php $Php2Html_FileUrl = $_SERVER["REQUEST_URI"]; $Php2Ht...

sourcesafe管理phpproj文件的补充说明(downmoon)

sourcesafe管理phpproj文件的补充说明(downmoon)

后来发现sourcesafe管理界面,(Admin登录),tools——Options——File Types——File Group——Add "PHP"——“*.php;*.phpp...

降低PHP Redis内存占用

降低PHP Redis内存占用

1、降低redis内存占用的优点  1、有助于减少创建快照和加载快照所用的时间  2、提升载入AOF文件和重写AOF文件时的效率  3、缩短从服务器进行同步所需的时间  4、无需添加额外...