溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP文件解壓和壓縮的方法

發(fā)布時間:2020-09-17 10:21:50 來源:億速云 閱讀:250 作者:小新 欄目:編程語言

這篇文章主要介紹了PHP文件解壓和壓縮的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

PHP壓縮和解壓文件需要有zip擴展---ZipArchive類

PHP ZipArchive類可用于壓縮和解壓縮。如果不存在,可能需要安裝該類。

從PHP 5.3開始,此擴展是內(nèi)置的。在此之前,Windows用戶需要在php.ini中啟用php_zip.dll才能使用其功能。

啟用步驟:

1、打開php.ini文件,添加

extension=php_zip.dll

2、保存后,重啟Apache或其他服務(wù)器。

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';
  //打開指定壓縮包,不存在則創(chuàng)建,存在則覆蓋
  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結(jié)尾
 * @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文件解壓和壓縮的方法內(nèi)容對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI