Note You need to install the zip extension
/**
* Compress individual files
* @method Zip_file
* @param string $filename file name
* @return Boolean True|false
*/
function Zip_file (string $filename) {
if (!is_file ($filename)) {
return false;
}
$zip =new ziparchive ();
$zipName =basename ($filename). Zip ';
Opens the specified compressed package, does not exist, is created, and exists overwrite
if ($zip->open ($zipName, ziparchive::create| Ziparchive::overwrite)) {
To add a file to a compressed package
if ($zip->addfile ($filename)) {
$zip->close ();
@unlink ($filename);
return true;
}else{
return false;
}
}else{
return false;
}
}
Var_dump (Zip_file (' 22.txt '));
Func_get_args
Test1.zip
/**
* Multi-File compression
* @method Zip_files
* @param string $zipName The name of the compressed package, end of. zip
* @param string $files need to compress the file name, can be multiple
* @return Boolean True|false
*/
function Zip_files (string $zipName,... $files) {
Detect if the package name is correct
$zipExt =strtolower (PathInfo ($zipName, pathinfo_extension));
if (' Zip '!== $zipExt) {
return false;
}
$zip =new ziparchive ();
if ($zip->open ($zipName, ziparchive::create| Ziparchive::overwrite)) {
foreach ($files as $file) {
if (Is_file ($file)) {
$zip->addfile ($file);
}
}
$zip->close ();
return true;
}else{
return false;
}
}
Var_dump (Zip_files (' Test1.zip ', ' 22.txt '));
Var_dump (Zip_files (' Test2.zip ', ' doupload.php ', ' download.html ', ' upload.html '));
/**
* Unzip
* @method Unzip_file
* @param string $zipName Zip package name
* Extract @param string $dest to the specified directory
* @return Boolean True|false
*/
function Unzip_file (string $zipName, String $dest) {
Detects if the compressed package exists to decompress
if (!is_file ($zipName)) {
return false;
}
Detects if the target path exists
if (!is_dir ($dest)) {
mkdir ($dest, 0777,true);
}
$zip =new ziparchive ();
if ($zip->open ($zipName)) {
$zip->extractto ($dest);
$zip->close ();
return true;
}else{
return false;
}
}
PHP Compressed Unzip files