注:PHP紧缩息争压文件须要有zip扩大---ZipArchive类
PHP ZipArchive类可用于紧缩息争紧缩。假如不存在,能够须要装置该类。
从PHP 5.3最先,此扩大是内置的。在此之前,Windows用户须要在php.ini中启用php_zip.dll才运用其功用。
启用步骤:
1、翻开php.ini文件,增加
extension=php_zip.dll
2、保留后,重启Apache或其他服务器。
PHP文件怎样解压?
/** * 解紧缩 * @method unzip_file * @param string $zipName 紧缩包称号 * @param string $dest 解压到指定目次 * @return boolean true|false */ function unzip_file(string $zipName,string $dest){ //检测要解压紧缩包是不是存在 if(!is_file($zipName)){ return false; } //检测目的途径是不是存在 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怎样紧缩文件?
示例1:紧缩单个文件
/** * 紧缩单个文件 * @method zip_file * @param string $filename 文件名 * @return boolean true|false */ function zip_file(string $filename){ if(!is_file($filename)){ return false; } $zip=new ZipArchive(); $zipName=basename($filename).'.zip'; //翻开指定紧缩包,不存在则建立,存在则掩盖 if($zip->open($zipName,ZipArchive::CREATE|ZipArchive::OVERWRITE)){ //将文件增加到紧缩包中 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
示例2:多文件紧缩
/** * 多文件紧缩 * @method zip_files * @param string $zipName 紧缩包的称号,.zip末端 * @param string $files 须要紧缩文件名,能够是多个 * @return boolean true|false */ function zip_files(string $zipName,...$files){ //检测紧缩包称号是不是准确 $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'));
相干视频教程引荐:《PHP教程》
以上就是PHP文件怎样解压和紧缩?(代码示例)的细致内容,更多请关注ki4网别的相干文章!