Home php教程 php手册 php文件打包 下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件

php文件打包 下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件

Jun 13, 2016 am 11:59 AM
php ziparchive download use compression Summarize Pack document of Bring your own

总结:                    

使用PHP下载文件的操作需要给出四个header(),可以参考我的另一篇博文:PHP如何实现下载功能超详细流程分析
计算文件的大小的时候,并不需要先打开文件,通过filesize($filename)就可以看出,如果需要先打开文件的话,filesize可能就会是这样的形式了filesize($filehandle)
向客户端回送数据的是,记得要设置一个buffer,用来指定每次向客户端输出多少数据,如:$buffer=1023。如果不指定的话,就会将整个文件全部写入内存当中,再一次性的讲数据传送给客户端
通过feof()函数,可以判断要读取的文件是否读完,如果还没读完,继续读取文件($file_data=fread()),并将数据回送给客户端(echo $file_data)
每次下载完成后,在客户端都会刷新下,说明了,其实每次都将数据写入到一个临时文件中,等全部下载完成后,再将所有的数据重新整合在一起
这里我使用的是绝对路径,绝对路径有个好处,就是适应性比较强,而且相对于相对路径,效率更高(免去了查找文件的过程)
分析下技术要点:                             

将文件打包成zip格式

下载文件的功能

要点解析:

这里我采用的是php自带的ZipArchive类
    a) 我们只需要new一个ZipArchive对象,然后使用open方法创建一个zip文件,接着使用addFile方法,将要打包的文件写入刚刚创建的zip文件中,最好还得记得关闭该对象。

    b) 注意点:使用open方法的时候,第二个参数$flags是可选的,$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()函数,客户端就知道该如何处理文件,是保存还是打开等等

最终的效果如下图所示:


复制代码 代码如下:


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 "<script>alert('当前目录不是有效目录');</script>";
}
}
/**
* 返回文件的大小
*
* @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$zip->addFile($this->currentdir.'/'.$items[$i],$items[$i]);
}
$zip->close();
$dw=new download($zipname.'.zip'); //下载文件
$dw->getfiles();
unlink($zipname.'.zip'); //下载完成后要进行删除
}
}
}
?>


复制代码 代码如下:


/**
* 下载文件
*
*/
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 "<script>alert('对不起,您要下载的文件不存在');</script>";
}
}
}
?>


页面显示的代码:

复制代码 代码如下:




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 "
当前目录下的所有文件";
?>








$res=$scandir->fileinfo;
foreach ($res as $k=>$v){
if (!($k=='.' || $k=='..')) {//过滤掉.和..
?>





}
}
?>




名称 大小(KB)


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles