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.
Iv. ZIPARCHIVE: CHECKCONS
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 ). <Br>
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:
Copy codeThe Code is as follows:
<? Php
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 ('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 <count ($ items); $ 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.
}
}
}
?>
Copy codeThe Code is as follows:
<? Php
/**
* 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:
Copy codeThe Code is as follows:
<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 the file into zip Format
}
Echo "current working directory:". $ scandir-> currentdir;
Echo "<br> all files in the 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>