PHP file packaging and downloading: Use the ZipArchive zip file that comes with PHP and download and package it

Source: Internet
Author: User
Tags ziparchive
PHP file packaging and downloading: Use the ZipArchive zip file that comes with PHP and download the packaged file. Summary:

Four headers () are required for downloading files using PHP. For more information, see my another blog post: how PHP implements the download function? Detailed Process Analysis
When calculating the file size, you do not need to open the file first. you can see through filesize ($ filename) that if you need to open the file first, filesize may be in this format: filesize ($ filehandle)
To send data back to the client, remember to set a buffer to specify how much data is output to the client each time, for example, $ buffer = 1023. If this parameter is not specified, the entire file will be written into the memory, and the data will be transferred to the client at one time.
The feof () function can be used to determine whether the file to be read has been read. if the file has not been read, continue to read the file ($ file_data = fread ()), and send the data back to the client (echo $ file_data)
After each download is complete, the client will refresh and explain that the data is written to a temporary file every time. after all the downloads are complete, all the data will be reintegrated.
Here, I use absolute paths. the advantage of absolute paths is that they are adaptable and more efficient than relative paths (eliminating the need to find files)
Analyze the following technical points:

Package files in zip format

Object downloading

Key points:

Here I use the ZipArchive class that comes with php.
A) we only need to create a new ZipArchive object, create a zip file using the open method, and then use the addFile method to write the file to be packaged into the zip file we just created, you 'd better remember to close this object.

B) Note: When using the open method, the second parameter $ flags is optional. $ flags is used to specify the processing method for opened zip files. There are four cases.

I. ZIPARCHIVE: OVERWRITE always creates a new file. if the specified zip file exists, it will OVERWRITE it.

Ii. ZIPARCHIVE: CREATE if the specified zip file does not exist, CREATE

Iii. ZIPARCHIVE: EXCL if the specified zip file exists, an error is returned.


File download process:

Work on the server:

The browser of the client sends a request to process the downloaded php file.
Note: Any operation must first be written to the memory. whether it is a video, audio, or text file, it must first be written to the memory.
In other words, it is essential to read files on the server into the memory of the server. (Note: I add double quotation marks to the server, it mainly indicates that the operations of this series are completed on the server ).

Since you want to write the file into the memory, you must first open the file
So here we need three File operation functions:
I. fopen ($ filename, $ mode)
II. fread (int $ handle, int $ length)
III. fclose (resource $ handle)

Client-side work:

Then, how can we transmit the file information that already exists in the server memory to the client?
The answer is that through the header () function, the client will know how to process the file, whether to save or open the file, and so on.

Shows the final effect:

The code is as follows:
Require './download. php ';
* Traverse directories and package them in zip format
Class traverseDir {
Public $ currentdir; // Current Directory
Public $ filename; // file name
Public $ fileinfo; // used to save all file names, directory names, and file sizes in the current directory
Public function _ construct (){
$ This-> currentdir = getcwd (); // return 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 ";
* Size of the returned file
* @ Param string $ filename file name
* @ Return file size (KB)
Public function getfilesize ($ fname ){
Returns filesize ($ fname)/1024;
* Compressed file (zip format)
Public function tozip ($ items ){
$ Zip = new ZipArchive ();
$ Zipname = date ('ymdhis ', time ());
If (! File_exists ($ zipname )){
$ Zip-> open(your 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 the object
$ Dw-> getfiles ();
Unlink(unzip zipname.'.zip '); // delete the file after the download is complete.

The code is as follows:
* Download an object
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;

// Obtain the file path (including the 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 two decimal places
// File download function
Public function getfiles (){
// Check whether the file exists
If (file_exists ($ this-> _ filepath )){
// Open the file
$ File = fopen ($ this-> _ filepath, "r ");
// Type of the returned file
Header ("Content-type: application/octet-stream ");
// Returns the value in bytes.
Header ("Accept-Ranges: bytes ");
// The size of the returned file
Header ("Accept-Length:". filesize ($ this-> _ filepath ));
// The pop-up dialog box for the client, corresponding file name
Header ("Content-Disposition: attachment; filename =". $ this-> _ filename );
// Transmit data to the client at one time before modification
Echo fread ($ file, filesize ($ this-> _ filepath ));
// After modification, only 1024 bytes of data are transmitted at a time to the client
// Send data back to the client
$ Buffer = 1024 ;//
// Judge 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 ";

Code displayed on the page:
The code is as follows:
Related Article

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: 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.