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();
?>

相关文章

11个PHPer必须要了解的编程规范

本文将讨论常用的良好的代码习惯,或者称为代码规范,在PHP领域。 1,错误报告开启 错误报告是在PHP中一个非常有用的功能,应同时在开发阶段启用。 这可以帮助我们确定我们的代码中的问题。...

php调用C代码的实现方法

在php程序中需要用到C代码,应该是下面两种情况: 1 已有C代码,在php程序中想直接用2 由于php的性能问题,需要用C来实现部分功能 针对第一种情况,最合适的方法是用system调...

PHP回调函数及匿名函数概念与用法详解

本文实例讲述了PHP回调函数及匿名函数概念与用法。分享给大家供大家参考,具体如下: 1、回调函数 PHP的回调函数其实和C、Java等语言的回调函数的作用是一模一样的,都是在主线程执行的...

php过滤所有的空白字符(空格、全角空格、换行等)

在php中自带的trim函数只能替换左右两端的空格,感觉在有些情况下不怎么好使,如果要将一个字符串中所有空白字符过滤掉(空格、全角空格、换行等),那么我们可以自己写一个过滤函数。 php...

PHP消息队列用法实例分析

本文实例讲述了PHP消息队列用法。分享给大家供大家参考,具体如下: 该消息队列用于linux下,进程通信 #根据路径和后缀创建一个id $key = ftok(__DIR__, 'R...