Home > Backend Development > PHP Tutorial > php实现文件下载实例分享_PHP

php实现文件下载实例分享_PHP

WBOY
Release: 2016-06-01 11:52:37
Original
811 people have browsed it

举一个案例:

复制代码 代码如下:
class Downfile {

    function downserver($file_name){
$file_path = "./img/".$file_name;
//转码,文件名转为gb2312解决中文乱码
$file_name = iconv("utf-8","gb2312",$file_name);
$file_path = iconv("utf-8","gb2312",$file_path);
$fp = fopen($file_path,"r") or exit("文件不存在");
//定义变量空着每次下载的大小
$buffer = 1024;
//得到文件的大小
$file_size = filesize($file_path);
//header("Content-type:text/html;charset=gb2312");
//会写用到的四条http协议信息
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");//可以忽略
header("Content-Length: ".$file_size);//原文这里是Accept-Length经查阅http协议无此项
header("Content-Disposition:attachment;filename=".$file_name);
//字节技术器,纪录当前现在字节数
$count = 0;
while(!feof($fp) && $file_size-$count>0){
//从$fp打开的文件流中每次读取$buffer大小的数据
$file_data = fread($fp,$buffer);
$count+=$buffer;
//将读取到的数据读取出来
echo $file_data;
}
//关闭文件流
fclose($fp);
    }

   }
?>

调用这个函数传入文件名就能对文件实现下载,不过要注意修改$file_path

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template