PHP ziparchive Package Compressed zip file instance

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

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 that is overwritten if the specified zip file exists

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

First, unzip the zip file

The code is as follows Copy Code

$zip = new ziparchive;//to create a Ziparchive object
/*
Handling Zip files through ziparchive objects
$zip->open The parameter of this method to represent the zip file name being processed.
If the operation of the zip file object succeeds, $zip->open this method returns True
*/
if ($zip->open (' test.zip ') = = TRUE)
{
$zip->extractto (' images ');//Suppose to unzip to a subfolder of the images folder under the current path PHP
$zip->close ()//Close the processed zip file
}

Compress the file into zip file

The code is as follows Copy Code

$zip = new Ziparchive;
/*
$zip->open The first parameter of this method represents the zip file name being processed.
The second parameter represents the processing mode, and ziparchive::overwrite means that if the zip file exists, it overwrites the original zip file.
If the parameter uses ziparchive::create, the system adds content to the original zip file.
If you are not adding content to a zip file multiple times, it is recommended that you use Ziparchive::overwrite.
With both parameters, if the zip file does not exist, the system will be automatically created.
If the operation of the zip file object succeeds, $zip->open this method returns True
*/
if ($zip->open (' Test.zip ', ziparchive::overwrite) = = TRUE)
{
$zip->addfile (' image.txt ');//Suppose the file name you added is Image.txt, under the current path
$zip->close ();
}

Third, file additions to the zip file

The code is as follows Copy Code
$zip = new Ziparchive;
$res = $zip->open (' Test.zip ', ziparchive::create);
if ($res = = TRUE) {
$zip->addfromstring (' test.txt ', ' file content goes here ');
$zip->close ();
echo ' OK ';
} else {
Echo ' failed ';
}

Example

To execute the packaged code:

  code is as follows copy code
import (' ORG. Util.filetozip ');
 //Package Download
  $cur _file =getcwd (). ' /dimg/2014052916/';
  $handler = Opendir ($cur _file);//$cur _file file directory
  $download _file = Array ();
  $i = 0;
&nb Sp;while (($filename = Readdir ($handler))!== false) {
 if ($filename!= '. ' && $filename!= ' ... ') {
  $download _file[$i + +] = $filename;
 }
 }
 closedir ($handler);
  $scandir =new traversedir ($cur _file, $save _path);//$save _path Zip package file directory
  $scandir->tozip ($ Download_file);

Filetozip class:

The code is as follows Copy Code
<?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 $savepath;
Public function __construct ($curpath, $savepath) {
$this->currentdir= $curpath;//Return to current directory
$this->savepath= $savepath;//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 ($savepath. $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 ', $savepath); Download files
$DW->getfiles ();
Unlink ($savepath. $zipname. Zip '); Delete when download is complete
}
}
}

/**
* Download files
*
*/
Class download{
protected $_filename;
protected $_filepath;
Protected $_filesize;//File Size
protected $savepath;//File size
Public function __construct ($filename, $savepath) {
$this->_filename= $filename;
$this->_filepath= $savepath. $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>";
}
}
}

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.