PHP file package download using PHP ziparchive compressed files and download packaged files _php tips

Source: Internet
Author: User
Tags fread php ziparchive ziparchive
Summarize:

The operation of using PHP to download files requires four headers () to refer to my other blog post: How PHP implements the download function hyper-Detailed process analysis
When calculating the size of a file, you do not need to open the file first, through FileSize ($filename) you can see that if you need to open the file first, filesize may be such a form of filesize ($filehandle)
To send data to the client, remember to set a buffer to specify how much data to output to the client at a 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
With the feof () function, you can determine whether the file you want to read is finished, and if you haven't finished reading it, continue reading the file ($file _data=fread ()) and send the data back to the client (echo $file _data)
After each download is completed, the client will be refreshed, the description, 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
I'm using an absolute path here, and the absolute path has the advantage of being more resilient and more efficient relative to relative paths (eliminating the process of locating files).
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:


Copy Code code as follows:

<?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-&GT;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
}
}
}
?>

Copy Code code as follows:

<?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 code that the page displays:
Copy Code code 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 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>

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.