PHP文件怎么解压和压缩?(代码示例)-php教程

资源魔 36 0
上面本篇文章就来给各人引见若何应用PHP对文件进行紧缩息争压操作,有着肯定的参考代价,如今分享给各人,有需求的冤家能够参考一下。

注:PHP紧缩息争压文件需求有zip扩大---ZipArchive类

PHP ZipArchive类可用于紧缩息争紧缩。假如没有存正在,可能需求装置该类。

从PHP 5.3开端,此扩大是内置的。正在此以前,Windows用户需求正在php.ini中启用php_zip.dll能力应用其性能。

启用步骤:

一、关上php.ini文件,增加

extension=php_zip.dll

二、保留后,重启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文件怎样解压以及紧缩?(代码示例)的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 文件压缩 文件解压

抱歉,评论功能暂时关闭!