Home >
Backend Development >
PHP Tutorial >
PHP file packaging Download and use PHP's own ZipArchive to compress the file and download the packaged file_PHP tutorial
PHP file packaging Download and use PHP's own ZipArchive to compress the file and download the packaged file_PHP tutorial
The operation of downloading a file using PHP requires four header(). You can refer to my other blog post: How PHP implements the download function. Super detailed process analysis When calculating the size of the file , you don’t need to open the file first. You can see from filesize($filename) that if you need to open the file first, filesize may be in the form filesize($filehandle) What sends data back to the client is , remember to set a buffer to specify how much data to output to the client each time, such as: $buffer=1023. If not specified, the entire file will be written into the memory, and the data will be transmitted to the client all at once Through the feof() function, you can determine whether the file to be read has been read. If it has not been read yet, After finishing, continue to read the file ($file_data=fread()), and send the data back to the client (echo $file_data) After each download is completed, the client will refresh, which shows that, in fact, every time Write the data into a temporary file, and after all downloads are completed, reintegrate all the data together Here I use absolute paths. The advantage of absolute paths is that they are more adaptable and relatively Compared with relative paths, it is more efficient (eliminating the process of finding files) Analyze the technical points:
Package files into zip format
Function of downloading files
Key points analysis:
Here I use the ZipArchive class that comes with php a) We only need to create a new ZipArchive object, and then use the open method to create a zip file. Then use the addFile method to write the file to be packaged into the zip file just created. It is best to remember to close the object.
b) Note: When using the open method, the second parameter $flags is optional. $flags is used to specify the processing method of the opened zip file. There are four situations
i. ZIPARCHIVE::OVERWRITE always creates a new file. If the specified zip file exists, it will be overwritten
ii. ZIPARCHIVE::CREATE If the specified zip file does not exist, a new one will be created.
iii. ZIPARCHIVE::EXCL If the specified zip file exists, an error will be reported
iv. ZIPARCHIVE::CHECKCONS
File downloading process:
Server-side work:
The client's browser sends a request to handle the downloaded php file. Note: Any operation needs to be written to the memory first. Whether it is a video, audio or text file, it needs to be written to the memory first. In other words, the operation of reading the files on the "server" into the memory of the "server" is essential (note: here I put the word server in double quotes, mainly to illustrate this A series of operations are completed on the server).
Since you want to write the file into the memory, you must open the file first So here are three file operation functions: One: fopen($filename,$ mode) Two: fread ( int $handle , int $length ) Three: fclose ( resource $handle )
Client side work:
So, how to pass the file information flow that already exists in the server-side memory to the client? The answer is through the header() function, the client knows how to process the file, whether to save or open, etc.
The final effect is as shown below:
Copy code The code is as follows:
require'./download.php'; /** * Traverse the directory and package it into zip format */ class traverseDir{ public $currentdir;//current directory public $filename;//File name public $fileinfo;//Used to save all file names and directory names and file sizes in the current directory public function __construct(){ $this- >currentdir=getcwd();//Return to the current directory } //Traverse the directory 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('The current directory is not a valid directory');</script>"; } } /** * Return the file size * * @param string $filename file name * @return file size (KB) */ public function getfilesize($fname){ return filesize($fname)/1024; } /** * Compressed file (zip format) */ public function tozip($items){ $zip=new ZipArchive(); $zipname=date('YmdHis',time()); if (!file_exists($zipname)){ $zip->open($zipname.'.zip',ZipArchive::OVERWRITE);//Create an empty zip file for ($i=0;$i$zip->addFile($this->currentdir.'/'.$items[$i],$items[$i]); } $zip- >close(); $dw=new download($zipname.'.zip'); //Download files $dw->getfiles(); unlink($zipname.'. zip'); //Delete after downloading } } } ?>
Copy code The code is as follows:
/** * Download file * */ class download{ protected $_filename; protected $_filepath; protected $_filesize;//File size public function __construct($filename){ $this->_filename=$filename; $this->_filepath=dirname( __FILE__).'/'.$filename; } //Get the file name public function getfilename(){ return $this->_filename; }
//Get the file path (including file name) public function getfilepath(){ return $this->_filepath; }
//Get the file size public function getfilesize(){ return $this->_filesize=number_format(filesize($this->_filepath)/(1024*1024),2);//Remove to two decimal places } //Function to download files public function getfiles(){ //Check whether the file exists if (file_exists($this->_filepath)){ //Open the file $file = fopen($this->_filepath,"r"); //Returned file type Header("Content-type: application/octet-stream"); / /Return according to byte size Header("Accept-Ranges: bytes"); //Return the size of the file Header("Accept-Length: ".filesize($this->_filepath) ); //Here is the pop-up dialog box for the client, the corresponding file name Header("Content-Disposition: attachment; filename=".$this->_filename); //Before modification , transmit data to the client at one time echo fread($file, filesize($this->_filepath)); //After modification, only 1024 bytes of data will be transmitted to the client at a time //Send data back to the client $buffer=1024;// //Determine whether the file has been read while (!feof($file)) { //Read the file into memory $file_data=fread($file,$buffer); //Send 1024 bytes of data back to the client each time echo $file_data; }
fclose($file); }else { echo "<script>alert('Sorry, the file you want to download does not exist');</script>"; } } } ?>
if (isset ($_POST['down_load'])){ $items=$_POST['items']; $scandir->tozip($items);//Compress the file into zip format } echo "Current working directory:".$scandir->currentdir; echo " All files in the current directory"; ?>
< ;form action="list.php" method="POST">
name
Size (KB)
$res=$scandir->fileinfo; foreach ($res as $k=>$v){ if (!($k=='.' || $k=='..')) {//Filter out . and . . ?>
} } ?> < ;tr>
table>
http://www.bkjia.com/PHPjc/325567.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325567.htmlTechArticleSummary: The operation of downloading files using PHP requires four header(), you can refer to my other article Blog post: How to implement the download function in PHP. Super detailed process analysis when calculating the file size...
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