File package, download using PHP's own ziparchive compressed files and download packaged files

Source: Internet
Author: User
Tags fread ziparchive

Summary:

    1. Using PHP to download the file needs to give four headers (), you can refer to my other blog post:how PHP implementation of the download function ultra-detailed process analysis
    2. Calculate the size of the file, do not need to open the file, through the FileSize ($filename) can be seen, if you need to open the file first, filesize may be the form of filesize ($filehandle)
    3. To send the data back to the client, remember to set a bufferthat specifies how much data to output to the client each time, such as: $buffer = 1023. If not specified, the entire file is written to memory, and once again the data is transmitted to the client
    4. with the feof () function, you can determine whether the file to be read is finished reading, continue reading the file ($file _data=fread ()), and send the data back to the client (echo $file _data) If you have not finished reading it
    5. after each download is completed, the client will be refreshed, indicating that, in fact, each time the data is written to a temporary file, and so on after all the download is complete, and then all the data back together
    6. Here I use absolute path, the absolute path has a benefit, is more adaptable, and relative to the relative path, more efficient (eliminating the process of finding files)
Technical Essentials Analysis:

    1. Package files into a zip format
    2. Features for downloading files

Key points of Analysis:

    1. Here I'm using PHP's own ziparchive class

A) We only need to new a Ziparchive object, then use the open method to create a zip file, and then use the AddFile method, the file will be packaged to write to 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 used to specify how to handle the open zip file in four different cases

I. Ziparchive::overwrite always creates a new file, and if the specified zip file exists, it will overwrite the

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 will be given

Iv. ziparchive::checkcons

Download the file flow:

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 necessary to read the file on the "server" into the memory of "server" (Note: Here I add the server three words with double quotation marks, mainly to explain the operation of this system class on the server to complete). <br>
Since you want to write the file into memory, you must first open the file
So here is the function of three file operations:
One: fopen ($filename, $mode)
II: fread (int $handle, int $length)
Three: fclose (Resource $handle)

---------------------------------------
Client-side work:
---------------------------------------
So, how to pass the file stream 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's saved or opened, and so on.

The final effect is as follows:

<?phprequire './download.php ';/** * Traverse directory, package into ZIP format */class traversedir{public $currentdir;//Current directory Publi c $filename;//file name public $fileinfo;//used to save all file names and directory names in the current directory and the size of the public function __construct () {$th IS-&GT;CURRENTDIR=GETCWD ()//return current directory}//Traverse directory Public Function Scandir ($filepath) {i                    F (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 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 <count ($items); $i + +) {$zip AddFile ($this->currentdir. '                /'. $items [$i], $items [$i]);                } $zip->close (); $DW =new Download ($zipname. Zip ');                Download file $dw->getfiles (); Unlink ($zipname. Zip '); Delete when download is complete}}}?>



<?php/** * * * * * * */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 (including file name) public function GetFilePath () {return $this->_filepath; }//Get file size public function GetFileSize () {return $this->_filesize=number_format (filesi Ze ($this->_filepath)/(1024*1024), 2);//to two bits after the decimal point}//function of the download file Public Function GetFiles () {/ /Check if file exists if (file_exists ($this->_filepath)) {//Open file $file = fopen ($this->_                filepath, "R");                Returns the file type Header ("Content-type:application/octet-stream");Returns the Header ("Accept-ranges:bytes") by byte size;                Returns the size of the file Header ("Accept-length:". FileSize ($this->_filepath)); Here the popup dialog box for the client, corresponding to the filename Header ("content-disposition:attachment;                Filename= ". $this->_filename);                Before modification, the data is transmitted to the client Echo fread ($file, FileSize ($this->_filepath));                After modification, only 1024 bytes of data are transmitted at a time to the client//client loopback data $buffer =1024;////Determine if the file is read                    while (!feof ($file)) {//reads the file into memory $file _data=fread ($file, $buffer);                Each time 1024 bytes of data is echoed to the client echo $file _data;            } fclose ($file);            }else {echo "<script>alert (' Sorry, the file you want to download does not exist ');</script>"; }}}?>



Page 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. And ...? > <tr> <td><input type= "checkbox" Name= "items[]" class= "filename" value= "<?php echo $k;? > "></td> &LT;TD&Gt;<?php echo $k;?></td> <td><?php Echo Number_format ($v [0],0);?></td> </tr&gt ; <?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>



File package, download using PHP's own ziparchive compressed files and download packaged files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.