一聚教程网:一个值得你收藏的教程网站

热门教程

PHP简单文件下载函数

时间:2022-06-24 21:27:46 编辑:袖梨 来源:一聚教程网

例子

 代码如下 复制代码

header("Content-Type; text/html; charset=utf-8");
class DownFile {
public static function File($_path,$file_name) {
//解决中文乱码问题
$_path=$_path.$file_name;
//判断文件是否存在
if (!file_exists($_path)) {
exit('文件不存在');
}
$_path=iconv('utf-8','gb2312',$_path);
$file_size=filesize($_path);
$fp=fopen($_path,'r');
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: $file_name");
header("Content-Disposition: attachment; filename=$file_name");
$buffer=1024;
$file_count=0;
while (!feof($fp) && ($file_size-$file_count>0)) {
$file_data=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_data;
}
fclose($fp);
}
}
//路径
$path='../';
//文件名
$file_name='filelist.php';
DownFile::File($path,$file_name);
?>

分析研究

使用header函数可以把像服务器端的脚本程序不需打包就可以进行下载了,像如php文件或html文件了,上面例子的核心语句是

 代码如下 复制代码

$_path=iconv('utf-8','gb2312',$_path);
$file_size=filesize($_path);
$fp=fopen($_path,'r');
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: $file_name");
header("Content-Disposition: attachment; filename=$file_name");
$buffer=1024;
$file_count=0;
while (!feof($fp) && ($file_size-$file_count>0)) {
$file_data=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_data;
}

下面三句,一个转换文件名编码这个防止中文乱码,第一个是获取文件大小,第三个是使用fopen读取文件

 代码如下 复制代码

$_path=iconv('utf-8','gb2312',$_path);
$file_size=filesize($_path);
$fp=fopen($_path,'r');

下面几行代码 是告诉浏览器我们要发送的文件是什么内容与文件名

 代码如下 复制代码

header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: $file_name");
header("Content-Disposition: attachment; filename=$file_name");


下面三行是告诉我们最大下载不能超过1MB第秒,并且循环一直下载,直到文件下载完毕即可

 代码如下 复制代码

$buffer=1024;
$file_count=0;
while (!feof($fp) && ($file_size-$file_count>0)) {
$file_data=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_data;

热门栏目