Analysis of the technical points:
Package files into zip format
The ability to download files
Key analysis:
Here I'm using PHP's own ziparchive class.
A We just need to new a Ziparchive object, then use the open method to create a zip file, and then use the AddFile method to write the file to be packaged in the zip file you just created, and it's best to remember to close the object.
B Note: When using the Open method, the second parameter $flags is optional, $flags to specify how to handle the open zip file, there are four different cases
I. Ziparchive::overwrite always creates a new file, and if the specified zip file exists, it overrides
Ii. ziparchive::create If the specified zip file does not exist, create a new
Iii. ZIPARCHIVE::EXCL If the specified zip file exists, an error is given
Iv. ziparchive::checkcons
--------------------------------------------------------------------------------
The process of downloading files:
Server-side work:
-------------------------------------------
The client's browser sends a request to the PHP file to process the download.
Note: Any operation needs to be written to memory first, whether it is video, audio, or text files, which need to be written into memory first.
In other words, it is essential to read the files on the server into the memory of the server (note: Here I enclose the server three words in double quotes, mainly to the server when the class is operating). <br>
Now that you want to write the file into memory, you must first open the file
So here's a function of three file operations:
One: fopen ($filename, $mode)
Two: fread (int $handle, int $length)
Three: fclose (Resource $handle)
---------------------------------------
Client-side work:
---------------------------------------
So how do you pass a file flow that already exists in the server-side memory to the client?
The answer is through the header () function, the client knows what to do with the file, whether it is saved or opened, and so on
The final effect is shown in the following illustration:
The code is as follows |
Copy Code |
<?php Require './download.php '; /** * Traverse directory, packaged into ZIP format */ Class traversedir{ public $currentdir;/current directory public $filename;//File name public $fileinfo;//To save all file names and directory names and file sizes under the current directory Public Function __construct () { $this->CURRENTDIR=GETCWD ();//Return to current directory } Traverse 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 (' current directory is not a valid directory ');</script>"; } } /** * Returns the size of the file * * @param string $filename filename * @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 <count ($items); $i + +) { $zip->addfile ($this->currentdir. /'. $items [$i], $items [$i]); } $zip->close (); $DW =new Download ($zipname. ') Zip '); Download files $DW->getfiles (); Unlink ($zipname. ') Zip '); Delete when download is complete } } } ?> |
The code is as follows |
Copy Code |
<?php /** * Download files * */ Class download{ protected $_filename; protected $_filepath; Protected $_filesize;//File Size Public function __construct ($filename) { $this->_filename= $filename; $this->_filepath=dirname (__file__). ' /'. $filename; } Get file name Public Function GetFileName () { return $this->_filename; }
Get file path (contains file name) Public Function GetFilePath () { return $this->_filepath; }
Get File size Public Function GetFileSize () { return $this->_filesize=number_format (filesize ($this->_filepath)/(1024*1024), 2);//go to two decimal places } The ability to download files Public Function GetFiles () { Check to see if a file exists if (file_exists ($this->_filepath)) { Open File $file = fopen ($this->_filepath, "R"); The file type returned Header ("Content-type:application/octet-stream"); return by byte size Header ("Accept-ranges:bytes"); Returns the size of a file Header ("Accept-length:" FileSize ($this->_filepath)); Here to the Client pop-up dialog, the corresponding file name Header ("content-disposition:attachment; Filename= ". $this->_filename); Data is transferred to the client at once before modification Echo fread ($file, FileSize ($this->_filepath)); After modification, only 1024 bytes of data are transmitted to the client at a time Loopback data to the client $buffer =1024;// Determine if the file is read out while (!feof ($file)) { Read the file into memory $file _data=fread ($file, $buffer); Send 1024 bytes of data to the client at a time echo $file _data; }
Fclose ($file); }else { echo "<script>alert (' Sorry, you want to download the file does not exist ');</script>"; } } } ?> |
The display code in the page is as follows
The code is as follows |
Copy Code |
<script type= "Text/javascript" src= "Jquery-1.7.2.js" ></script> <script type= "Text/javascript" src= "Ajax.js" ></script> <?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);//compress files into zip format } echo "Current working directory:". $scandir->currentdir; echo "<br> All files in current directory"; ?>
<form action= "list.php" method= "POST" > <table> <tr> <td></td> <td> name </td> <td> size (KB) </td> </tr> <?php $res = $scandir->fileinfo; foreach ($res as $k => $v) { if (!) ( $k = = '. ' | | $k = = '.. ') {//filter out. ?> <tr> <td><input type= "checkbox" Name= "items[]" class= "filename" value= "<?php echo $k;? > "></td> <td><?php echo $k;?></td> <td><?php Echo Number_format ($v [0],0);?></td> </tr> <?php } } ?> <tr> <td><input type= "checkbox" id= "Selall" ><label for= "Selall" > select all </label></td> <td><input type= "Submit" Name= "Down_load" value= "package and download" id= "TOZIP_TETTTT" ></td> </tr> </table> </form> |
Summarize:
--------------------------------------------------------------------------------
Using PHP to download files requires four headers () to refer to my other blog post: How PHP implements the download feature hyper-Detailed process Analysis
calculates the size of a file without first opening the file through FileSize ($filename) You can see that if you need to open the file first, FileSize might be the form filesize ($filehandle)
Loopback data to the client, remember to set a buffer that specifies how much data to output to the client each time, such as: $ buffer=1023. If you do not specify, the entire file will be written to memory, and once again the data transferred to the client
through the feof () function, you can determine whether to read the file read, if not finished reading, continue to read the file ($file _data=fread ()), and sends the data back to the client (echo $file _data)
After each download is completed, in the client will be refreshed, that is, in fact, each time the data is written to a temporary file, and so on all the download completed, and then all the data back together again
here I use the absolute path, An absolute path has the advantage of being more resilient and more efficient than relative paths (eliminating the process of locating files)