国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 php文件打包 下載之使用PHP自帶的ZipArchive壓縮文件并下載打包好的文件

php文件打包 下載之使用PHP自帶的ZipArchive壓縮文件并下載打包好的文件

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

總結(jié):                    

使用PHP下載文件的操作需要給出四個header(),可以參考我的另一篇博文:PHP如何實現(xiàn)下載功能超詳細(xì)流程分析
計算文件的大小的時候,并不需要先打開文件,通過filesize($filename)就可以看出,如果需要先打開文件的話,filesize可能就會是這樣的形式了filesize($filehandle)
向客戶端回送數(shù)據(jù)的是,記得要設(shè)置一個buffer,用來指定每次向客戶端輸出多少數(shù)據(jù),如:$buffer=1023。如果不指定的話,就會將整個文件全部寫入內(nèi)存當(dāng)中,再一次性的講數(shù)據(jù)傳送給客戶端
通過feof()函數(shù),可以判斷要讀取的文件是否讀完,如果還沒讀完,繼續(xù)讀取文件($file_data=fread()),并將數(shù)據(jù)回送給客戶端(echo $file_data)
每次下載完成后,在客戶端都會刷新下,說明了,其實每次都將數(shù)據(jù)寫入到一個臨時文件中,等全部下載完成后,再將所有的數(shù)據(jù)重新整合在一起
這里我使用的是絕對路徑,絕對路徑有個好處,就是適應(yīng)性比較強,而且相對于相對路徑,效率更高(免去了查找文件的過程)
分析下技術(shù)要點:                             

將文件打包成zip格式

下載文件的功能

要點解析:

這里我采用的是php自帶的ZipArchive類
    a) 我們只需要new一個ZipArchive對象,然后使用open方法創(chuàng)建一個zip文件,接著使用addFile方法,將要打包的文件寫入剛剛創(chuàng)建的zip文件中,最好還得記得關(guān)閉該對象。

    b) 注意點:使用open方法的時候,第二個參數(shù)$flags是可選的,$flags用來指定對打開的zip文件的處理方式,共有四種情況

  i. ZIPARCHIVE::OVERWRITE 總是創(chuàng)建一個新的文件,如果指定的zip文件存在,則會覆蓋掉

ii. ZIPARCHIVE::CREATE 如果指定的zip文件不存在,則新建一個

iii. ZIPARCHIVE::EXCL 如果指定的zip文件存在,則會報錯

iv. ZIPARCHIVE::CHECKCONS

下載文件的流程:                              

服務(wù)器端的工作:

客戶端的瀏覽器發(fā)送一個請求到處理下載的php文件。
注意:任何一個操作都首先需要寫入到內(nèi)存當(dāng)中,不管是視頻、音頻還是文本文件,都需要先寫入到內(nèi)存當(dāng)中。
換句話說,將“服務(wù)器”上的文件讀入到“服務(wù)器”的內(nèi)存當(dāng)中的這個操作時必不可少的(注意:這里我將服務(wù)器三個字加上雙引號,主要是說明這一系類的操作時在服務(wù)器上完成的)。

既然要將文件寫入到內(nèi)存當(dāng)中,就必然要先將文件打開
所以這里就需要三個文件操作的函數(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)建一個空的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'); //下載完成后要進(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ù)點后兩位
}
//下載文件的功能
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個字節(jié)的數(shù)據(jù)給客戶端
//向客戶端回送數(shù)據(jù)
$buffer=1024;//
//判斷文件是否讀完
while (!feof($file)) {
//將文件讀入內(nèi)存
$file_data=fread($file,$buffer);
//每次向客戶端回送1024個字節(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)前目錄下的所有文件";
?>








$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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

Your First PHP Script: A Practical Introduction Your First PHP Script: A Practical Introduction Jul 16, 2025 am 03:42 AM

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

What is PHP and What is it Used For? What is PHP and What is it Used For? Jul 16, 2025 am 03:45 AM

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

PHP 8 Installation Guide PHP 8 Installation Guide Jul 16, 2025 am 03:41 AM

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How Do You Handle File Operations (Reading/Writing) in PHP? How Do You Handle File Operations (Reading/Writing) in PHP? Jul 16, 2025 am 03:48 AM

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

See all articles