php文件打包 下載之使用PHP自帶的ZipArchive壓縮文件并下載打包好的文件
Jun 13, 2016 am 11:59 AM
總結(jié):
使用PHP下載文件的操作需要給出四個(gè)header(),可以參考我的另一篇博文:PHP如何實(shí)現(xiàn)下載功能超詳細(xì)流程分析
計(jì)算文件的大小的時(shí)候,并不需要先打開文件,通過filesize($filename)就可以看出,如果需要先打開文件的話,filesize可能就會(huì)是這樣的形式了filesize($filehandle)
向客戶端回送數(shù)據(jù)的是,記得要設(shè)置一個(gè)buffer,用來指定每次向客戶端輸出多少數(shù)據(jù),如:$buffer=1023。如果不指定的話,就會(huì)將整個(gè)文件全部寫入內(nèi)存當(dāng)中,再一次性的講數(shù)據(jù)傳送給客戶端
通過feof()函數(shù),可以判斷要讀取的文件是否讀完,如果還沒讀完,繼續(xù)讀取文件($file_data=fread()),并將數(shù)據(jù)回送給客戶端(echo $file_data)
每次下載完成后,在客戶端都會(huì)刷新下,說明了,其實(shí)每次都將數(shù)據(jù)寫入到一個(gè)臨時(shí)文件中,等全部下載完成后,再將所有的數(shù)據(jù)重新整合在一起
這里我使用的是絕對路徑,絕對路徑有個(gè)好處,就是適應(yīng)性比較強(qiáng),而且相對于相對路徑,效率更高(免去了查找文件的過程)
分析下技術(shù)要點(diǎn):
將文件打包成zip格式
下載文件的功能
要點(diǎn)解析:
這里我采用的是php自帶的ZipArchive類
a) 我們只需要new一個(gè)ZipArchive對象,然后使用open方法創(chuàng)建一個(gè)zip文件,接著使用addFile方法,將要打包的文件寫入剛剛創(chuàng)建的zip文件中,最好還得記得關(guān)閉該對象。
b) 注意點(diǎn):使用open方法的時(shí)候,第二個(gè)參數(shù)$flags是可選的,$flags用來指定對打開的zip文件的處理方式,共有四種情況
i. ZIPARCHIVE::OVERWRITE 總是創(chuàng)建一個(gè)新的文件,如果指定的zip文件存在,則會(huì)覆蓋掉
ii. ZIPARCHIVE::CREATE 如果指定的zip文件不存在,則新建一個(gè)
iii. ZIPARCHIVE::EXCL 如果指定的zip文件存在,則會(huì)報(bào)錯(cuò)
iv. ZIPARCHIVE::CHECKCONS
下載文件的流程:
服務(wù)器端的工作:
客戶端的瀏覽器發(fā)送一個(gè)請求到處理下載的php文件。
注意:任何一個(gè)操作都首先需要寫入到內(nèi)存當(dāng)中,不管是視頻、音頻還是文本文件,都需要先寫入到內(nèi)存當(dāng)中。
換句話說,將“服務(wù)器”上的文件讀入到“服務(wù)器”的內(nèi)存當(dāng)中的這個(gè)操作時(shí)必不可少的(注意:這里我將服務(wù)器三個(gè)字加上雙引號,主要是說明這一系類的操作時(shí)在服務(wù)器上完成的)。
既然要將文件寫入到內(nèi)存當(dāng)中,就必然要先將文件打開
所以這里就需要三個(gè)文件操作的函數(shù)了:
一:fopen($filename ,$mode)
二:fread ( int $handle , int $length )
三:fclose ( resource $handle )
客戶端端的工作:
那么,如何將已經(jīng)存在于服務(wù)器端內(nèi)存當(dāng)中的文件信息流,傳給客戶端呢?
答案是通過header()函數(shù),客戶端就知道該如何處理文件,是保存還是打開等等
最終的效果如下圖所示:
復(fù)制代碼 代碼如下:
require'./download.php';
/**
* 遍歷目錄,打包成zip格式
*/
class traverseDir{
public $currentdir;//當(dāng)前目錄
public $filename;//文件名
public $fileinfo;//用于保存當(dāng)前目錄下的所有文件名和目錄名以及文件大小
public function __construct(){
$this->currentdir=getcwd();//返回當(dāng)前目錄
}
//遍歷目錄
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('當(dāng)前目錄不是有效目錄');</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);//創(chuàng)建一個(gè)空的zip文件
for ($i=0;$i
}
$zip->close();
$dw=new download($zipname.'.zip'); //下載文件
$dw->getfiles();
unlink($zipname.'.zip'); //下載完成后要進(jìn)行刪除
}
}
}
?>
復(fù)制代碼 代碼如下:
/**
* 下載文件
*
*/
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);//去小數(shù)點(diǎn)后兩位
}
//下載文件的功能
public function getfiles(){
//檢查文件是否存在
if (file_exists($this->_filepath)){
//打開文件
$file = fopen($this->_filepath,"r");
//返回的文件類型
Header("Content-type: application/octet-stream");
//按照字節(jié)大小返回
Header("Accept-Ranges: bytes");
//返回文件的大小
Header("Accept-Length: ".filesize($this->_filepath));
//這里對客戶端的彈出對話框,對應(yīng)的文件名
Header("Content-Disposition: attachment; filename=".$this->_filename);
//修改之前,一次性將數(shù)據(jù)傳輸給客戶端
echo fread($file, filesize($this->_filepath));
//修改之后,一次只傳輸1024個(gè)字節(jié)的數(shù)據(jù)給客戶端
//向客戶端回送數(shù)據(jù)
$buffer=1024;//
//判斷文件是否讀完
while (!feof($file)) {
//將文件讀入內(nèi)存
$file_data=fread($file,$buffer);
//每次向客戶端回送1024個(gè)字節(jié)的數(shù)據(jù)
echo $file_data;
}
fclose($file);
}else {
echo "<script>alert('對不起,您要下載的文件不存在');</script>";
}
}
}
?>
頁面顯示的代碼:
復(fù)制代碼 代碼如下:
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 "當(dāng)前的工作目錄:".$scandir->currentdir;
echo "
當(dāng)前目錄下的所有文件";
?>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

The key to writing PHP comments is clear, useful and concise. 1. Comments should explain the intention behind the code rather than just describing the code itself, such as explaining the logical purpose of complex conditional judgments; 2. Add comments to key scenarios such as magic values, old code compatibility, API interfaces, etc. to improve readability; 3. Avoid duplicate code content, keep it concise and specific, and use standard formats such as PHPDoc; 4. Comments should be updated synchronously with the code to ensure accuracy. Good comments should be thought from the perspective of others, reduce the cost of understanding, and become a code understanding navigation device.
