Php generates two examples of zip files

Source: Internet
Author: User
Tags ziparchive

To generate a zip file in php, we only need to use a php zip compression ZipArchive function. The following small series will summarize the two implementations. One is to use ZipArchive to generate a zip file, all files in another compressed folder.

Note:

ZipArchive to compress files. This is an extension class of php. It has been supported since php5.2. If you encounter an error while using it, check php. in ini, have you removed the semicolon before extension = php_zip.dll, and then restart Apache to use this class library.

Example 1

Generate zip compressed files

The Code is as follows: Copy code

<? Php
/* Generate a zip compressed file */
Function create_zip ($ files = array (), $ destination = '', $ overwrite = false ){
// If the zip file already exists and overwrite is false, return false
If (file_exists ($ destination )&&! $ Overwrite) {return false ;}
// Vars
$ Valid_files = array ();
// If files were passed in...
If (is_array ($ files )){
// Cycle through each file
Foreach ($ files as $ file ){
// Make sure the file exists
If (file_exists ($ file )){
$ Valid_files [] = $ file;
}
}
}
// If we have good files...
If (count ($ valid_files )){
// Create the archive
$ Zip = new ZipArchive ();
If ($ zip-> open ($ destination, $ overwrite? ZIPARCHIVE: OVERWRITE: ZIPARCHIVE: CREATE )! = True ){
Return false;
}
// Add the files
Foreach ($ valid_files as $ file ){
$ File_info_arr = pathinfo ($ file );
$ Zip-> addFile ($ file, $ file_info_arr ['basename']); // remove the hierarchical directory
}
// Debug
// Echo The zip archive ins INS, $ zip-> numFiles, 'files with a status of ', $ zip-> status;

// Close the zip -- done!
$ Zip-> close ();

// Check to make sure the file exists
Return file_exists ($ destination );
}
Else
{
Return false;
}
}

Define ('rootpath', dirname (_ FILE _); // website path

$ Files_to_zip = array (
Rootpath.directory_separator.'php?jquery=cookbook ',
ROOTPATH.DIRECTORY_SEPARATOR.'TurboListerZeroTemplate.csv'
);
// If true, good; if false, zip creation failed
Using filename='my-archive.zip ';
$ Result = create_zip ($ files_to_zip, $ filename );

Example 2

Compress all files in the folder

The Code is as follows: Copy code

<? Php
/*
All files in the zip compressed php folder
*/
Class HZip
{
/**
* Add files and subdirectories to a zip file.
* @ Param string $ folder
* @ Param ZipArchive $ zipFile
* @ Param int $ exclusiveLength Number of text to be exclusived from the file path.
*/
Private static function folderToZip ($ folder, & $ zipFile, $ exclusiveLength ){
$ Handle = opendir ($ folder );
While (false! ==$ F = readdir ($ handle )){
If ($ f! = '.' & $ F! = '..'){
$ FilePath = "$ folder/$ f ";
// Remove prefix from file path before add to zip.
$ LocalPath = substr ($ filePath, $ exclusiveLength );
If (is_file ($ filePath )){
$ ZipFile-> addFile ($ filePath, $ localPath );
} Elseif (is_dir ($ filePath )){
// Add a subfolder
$ ZipFile-> addEmptyDir ($ localPath );
Self: folderToZip ($ filePath, $ zipFile, $ exclusiveLength );
}
}
}
Closedir ($ handle );
}

/**
* Zip a folder (include itself ).
* Usage:
* HZip: zipDir ('/path/to/sourcedir','/path/to/out.zip ');
*
* @ Param string $ sourcePath Path of directory to be zip.
* @ Param string $ outZipPath Path of output zip file.
*/
Public static function zipDir ($ sourcePath, $ outZipPath)
{
$ PathInfo = pathInfo ($ sourcePath );
$ ParentPath = $ pathInfo ['dirname'];
$ DirName = $ pathInfo ['basename'];
$ SourcePath = $ parentPath. '/'. $ dirName; // prevents the bug of passing the 'folder' folder
$ Z = new ZipArchive ();
$ Z-> open ($ outZipPath, ZIPARCHIVE: CREATE); // CREATE a zip file
$ Z-> addEmptyDir ($ dirName); // create a folder
Self: folderToZip ($ sourcePath, $ z, strlen ("$ parentPath /"));
$ Z-> close ();
}
}

// Usage
HZip: zipDir ('yourlife', 'yourlife.zip ');
?>

/******** Optional ziparchive parameter *******/
/*
1. ZipArchive: addEmptyDir

Add a new file directory

2. ZipArchive: addFile

Add the file to the specified zip package.

3. ZipArchive: addFromString

Add the content to the added file at the same time.

4. ZipArchive: close

Disable ziparchive

5. ZipArchive: extrac.pdf

Decompress the package

6. ZipArchive: open

Open a zip package

7. ZipArchive: getStatusString

Returns the status content during compression, including error information and compression information.

8. ZipArchive: deleteIndex

Delete a file in the compressed package, for example, deleteIndex (0). Delete the first file.

9. ZipArchive: deleteName

Delete a file name in the package and delete the file.
......
*/

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.