PHP文件打包下载技术总结
总结:
在PHP中执行文件下载操作时,必须正确配置四个关键的header()函数,具体流程可参考相关博文《PHP如何实现下载功能超详细流程分析》。
获取文件大小无需先打开文件句柄,直接调用filesize($filename)即可;若需通过句柄获取,函数形式应为filesize($filehandle)。
向客户端回送数据的是,记得要设置一个buffer,用来指定每次向客户端输出多少数据,如:$buffer=1023。如果不指定的话,就会将整个文件全部写入内存当中,再一次性的讲数据传送给客户端
利用feof()函数检测文件读取状态,若未读完则继续执行$fread()读取数据,并通过echo语句将数据回传给客户端。
每次下载完成后客户端界面的刷新现象表明,浏览器实际上是将接收到的数据先写入临时文件,待全部下载结束后再整合为最终文件。
代码中使用绝对路径具有更强的适应性,且相比相对路径效率更高,因为它省去了系统查找文件路径的过程。
技术要点分析如下:
将选定文件打包为zip格式。
实现文件下载功能。
要点解析:
本方案采用PHP原生扩展提供的ZipArchive类进行压缩操作。
a) 基本流程:实例化ZipArchive对象,调用open方法创建zip文件,使用addFile方法将目标文件加入压缩包,最后记得关闭对象以释放资源。
b) 注意事项:open方法的第二个参数$flags用于指定对已存在zip文件的处理策略,该参数可选,共有四种取值情况。
i. ZIPARCHIVE::OVERWRITE:始终创建新文件,若目标zip已存在则直接覆盖。
ii. ZIPARCHIVE::CREATE:若目标zip文件不存在,则新建一个。
iii. ZIPARCHIVE::EXCL:若目标zip文件已存在,则报错终止。
iv. ZIPARCHIVE::CHECKCONS:检查一致性。
下载文件的完整流程:
服务器端的工作:
客户端浏览器发送请求至处理下载的PHP脚本。
注意:任何类型的文件(视频、音频或文本)在传输前都必须先被读取到内存中。
换言之,将“服务器”上的物理文件读入“服务器”内存的操作是不可或缺的(此处强调双引号意在说明该系列操作均在服务器端完成)。
既然需要将文件写入内存,就必须先打开文件句柄。
因此需要用到以下三个文件操作函数:
一:fopen($filename, $mode)
二:fread(int $handle, int $length)
三:fclose(resource $handle)
客户端的工作:
如何将存在于服务器内存中的文件信息流传递给客户端?
答案是通过header()函数告知客户端如何处理文件,例如选择保存还是直接打开。
最终效果如下图所示:

<?php
require'./download.php';
/**
* 遍历目录,打包成zip格式
*/
class traverseDir{
public $currentdir;//当前目录
public $filename;//文件名
public $fileinfo;//用于保存当前目录下的所有文件名和目录名以及文件大小
public function __construct(){
$this->currentdir=getcwd();//返回当前目录
}
//遍历目录
public function scandir($filepath){
if (is_dir($filepath)){
$arr=scandir($filepath);
foreach ($arr as $k=>$v){
$this->fileinfo[$v][]=$this->getfilesize($v);
}
}else {
echo "";
}
}
/**
* 返回文件的大小
*
* @param string $filename 文件名
* @return 文件大小(KB)
*/
public function getfilesize($fname){
return filesize($fname)/1024;
}
/**
* 压缩文件(zip格式)
*/
public function tozip($items){
$zip=new ZipArchive();
$zipname=date('YmdHis',time());
if (!file_exists($zipname)){
$zip->open($zipname.'.zip',ZipArchive::OVERWRITE);//创建一个空的zip文件
for ($i=0;$i< count>$zip->addFile($this->currentdir.'/'.$items[$i],$items[$i]); } $zip->close(); $dw=new download($zipname.'.zip'); //下载文件 $dw->getfiles(); unlink($zipname.'.zip'); //下载完成后要进行删除 } } } ?>$zip->addFile($this->currentdir.'/'.$items[$i],$items[$i]); }
$zip->close();
$dw=new download($zipname.'.zip'); //下载文件
$dw->getfiles();
unlink($zipname.'.zip'); //下载完成后要进行删除
}
}
}
?>
<?php
/**
* 下载文件
*
*/
class download{
protected $_filename;
protected $_filepath;
protected $_filesize;//文件大小
public function __construct($filename){
$this->_filename=$filename;
$this->_filepath=dirname(__FILE__).'/'.$filename;
}
//获取文件名
public function getfilename(){
return $this->_filename;
}
//获取文件路径(包含文件名)
public function getfilepath(){
return $this->_filepath;
}
//获取文件大小
public function getfilesize(){
return $this->_filesize=number_format(filesize($this->_filepath)/(1024*1024),2);//去小数点后两位
}
//下载文件的功能
public function getfiles(){
//检查文件是否存在
if (file_exists($this->_filepath)){
//打开文件
$file = fopen($this->_filepath,"r");
//返回的文件类型
Header("Content-type: application/octet-stream");
//按照字节大小返回
Header("Accept-Ranges: bytes");
//返回文件的大小
Header("Accept-Length: ".filesize($this->_filepath));
//这里对客户端的弹出对话框,对应的文件名
Header("Content-Disposition: attachment; filename=".$this->_filename);
//修改之前,一次性将数据传输给客户端
echo fread($file, filesize($this->_filepath));
//修改之后,一次只传输1024个字节的数据给客户端
//向客户端回送数据
$buffer=1024;//
//判断文件是否读完
while (!feof($file)) {
//将文件读入内存
$file_data=fread($file,$buffer);
//每次向客户端回送1024个字节的数据
echo $file_data;
}
fclose($file);
}else {
echo "";
}
}
}
?> 页面显示的代码:
<?php
header("Content-type:text/html;charset=utf8");
require('./getfile.php');
$scandir=new traverseDir();
$scandir->scandir($scandir->currentdir);
$scandir->currentdir;
if (isset($_POST['down_load'])){
$items=$_POST['items'];
$scandir->tozip($items);//将文件压缩成zip格式
}
echo "当前的工作目录:".$scandir->currentdir;
echo "
当前目录下的所有文件";
?> <form action="list.php" method="POST"> <br><table> <BR><tr> <BR><td></td> <BR><td>名称</td> <BR><td>大小(KB)</td> <BR></tr> <BR><?php <BR>$res=$scandir->fileinfo; <BR>foreach ($res as $k=>$v){ <BR>if (!($k=='.' || $k=='..')) {//过滤掉.和.. <BR>?> <BR><tr> <BR><td><input type="checkbox" name="items[]" class="filename" value="<?php echo $k;?>"></td> <BR><td><?php echo $k; ?></td> <BR><td><?php echo number_format($v[0],0); ?></td> <BR></tr> <BR><?php <BR>} <BR>} <BR>?> <BR><tr> <BR><td><input type="checkbox" id="selall"><label for="selall">全选</label></td> <BR><td><input type="submit" name="down_load" value="打包并下载" id="tozip_tetttt"></td> <BR></tr> <BR></table> <br></form>