zoukankan      html  css  js  c++  java
  • php解压缩文件方法汇总

    一  使用内部扩展实现(>=php5)

            ①解压缩文件

           

      function unzip_file($file, $destination){ 
      // create object 
      $zip = new ZipArchive() ; 
      // open archive 
      if ($zip->open($file) !== TRUE) { 
      die ('Could not open archive'); 
      } 
      // extract contents to destination directory 
      $zip->extractTo($destination); 
      // close archive 
      $zip->close(); 
      echo 'Archive extracted to directory'; 
     } 

     unzip_file('./a.zip','bs');

      ②生成压缩文件
    /* creates a compressed zip 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) { 
    $zip->addFile($file,$file); 

    //debug 
    //echo 'The zip archive contains ',$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; 


    /***** Example Usage ***/ 
    $files=array('showdir.php', 'suanfa.php', 'word.php'); 
    create_zip($files, 'myzipfile.zip'); 

    二   不使用组件    完全使用php内部函数

    解压代码:

     public function ExtractFile($header,$to,$zip) {
      $header = $this->readfileheader($zip);

      if (substr($to,-1)!="/") $to.="/";
      if ($to=='./') $to = '';
      $pth = explode("/",$to.$header['filename']);
      $mydir = '';
      for($i=0;$i<count($pth)-1;$i++) {
       if (!$pth[$i]) continue;
       $mydir .= $pth[$i]."/";
       if ((!is_dir($mydir) && @mkdir($mydir,0777)) || (($mydir==$to.$header['filename'] || ($mydir==$to && $this->total_folders==0)) && is_dir($mydir)) ) {
        @chmod($mydir,0777);
        $this->total_folders ++;
        echo 'Extract : ',$mydir,'<br>';
       }
      }

      if (strrchr($header['filename'],'/')=='/') return;
      if (!($header['external']==0x41FF0010)&&!($header['external']==16)) {
       if ($header['compression']==0) {
        $fp = @fopen($to.$header['filename'], 'wb');
        if (!$fp) return(-1);
        $size = $header['compressed_size'];
        while ($size != 0) {
         $read_size = ($size < 2048 ? $size : 2048);
         $buffer = fread($zip, $read_size);
         $binary_data = pack('a'.$read_size, $buffer);
         @fwrite($fp, $binary_data, $read_size);
         $size -= $read_size;
        }
        fclose($fp);
        touch($to.$header['filename'], $header['mtime']);
       } else {
        $fp = @fopen($to.$header['filename'].'.gz','wb');
        if (!$fp) return(-1);
        $binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']),
        Chr(0x00), time(), Chr(0x00), Chr(3));

        fwrite($fp, $binary_data, 10);
        $size = $header['compressed_size'];

        while ($size != 0) {
         $read_size = ($size < 1024 ? $size : 1024);
         $buffer = fread($zip, $read_size);
         $binary_data = pack('a'.$read_size, $buffer);
         @fwrite($fp, $binary_data, $read_size);
         $size -= $read_size;
        }

        $binary_data = pack('VV', $header['crc'], $header['size']);
        fwrite($fp, $binary_data,8); fclose($fp);

        $gzp = @gzopen($to.$header['filename'].'.gz','rb') or die("Cette archive est compress")

    更多详细内容请查看:http://www.111cn.net/phper/22/e13f0575bdd4d22d83ed67e3fbeab58d.htm

    压缩代码:

    class PHPZip{
     var $dirInfo = array("0","0");
     var $rootDir = '';
     var $datasec      = array();
     var $ctrl_dir     = array();
     var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
     var $old_offset   = 0;

     function downloadZip(){
      createZip($dir, $zipfilename, true);
     }
     function createZip($dir, $zipfilename, $autoDownload = false){
      if (@function_exists('gzcompress')){
       @set_time_limit("0");
       if (is_array($dir)){
        $fd = fopen ($dir, "r");
        $fileValue = fread ($fd, filesize ($filename));
        fclose ($fd);
        if (is_array($dir)) $filename = basename($dir);
        $this -> addFile($fileValue, "$filename");
       }else{
        $this->dirTree($dir,$dir);
       }

       $zipfilenametemp = time().$zipfilename;
       $out = $this -> filezip();
       $fp = fopen($zipfilenametemp, "w");
       fwrite($fp, $out, strlen($out));
       fclose($fp);
       $filesize = filesize($zipfilenametemp);

       if ($filesize < 104857600) {
        if($autoDownload){
         header("Content-type: application/octet-stream");
         header("Content-disposition: attachment; filename=".$zipfilename);
        }
        echo $this -> filezip();
       }else{
        echo "create zip error!";
       }
       unlink($zipfilenametemp);
      }
      }
     //get dir tree..
     function dirTree($directory,$rootDir){
      global $_SERVER,$dirInfo,$rootDir;

      $fileDir=$rootDir;
      $myDir=dir($directory);
      while($file=$myDir->read()){
       if(is_dir("$directory/$file") and $file!="." and $file!=".."){
        $dirInfo[0]++;
        $rootDir ="$fileDir$file/";

        $this -> addFile('', "$rootDir");

        //go on n's folders
        $this->dirTree("$directory/$file",$rootDir);
       }else{
        if($file!="." and $file!=".."){
         $dirInfo[1]++;
         //$fd = fopen ("$directory/$file", "r");
         $fileValue = file_get_contents("$directory/$file");
         //fclose ($fd);
         $this -> addFile($fileValue, "$fileDir$file");
        }
       }
      }
      $myDir->close();
     }
        function unix2DosTime($unixtime = 0) {
            $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

            if ($timearray['year'] < 1980) {
              $timearray['year']    = 1980;
              $timearray['mon']     = 1;
              $timearray['mday']    = 1;
              $timearray['hours']   = 0;
              $timearray['minutes'] = 0;
              $timearray['seconds'] = 0;
            } // end if

            return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                    ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
        }
        function addFile($data, $name, $time = 0){
            $name     = str_replace('\', '/', $name);

            $dtime    = dechex($this->unix2DosTime($time));
            $hexdtime = 'x' . $dtime[6] . $dtime[7]
                      . 'x' . $dtime[4] . $dtime[5]
                      . 'x' . $dtime[2] . $dtime[3]
                      . 'x' . $dtime[0] . $dtime[1];
            eval('$hexdtime = "' . $hexdtime . '";');

            $fr   = "x50x4bx03x04";
            $fr   .= "x14x00";            // ver needed to extract
            $fr   .= "x00x00";            // gen purpose bit flag
            $fr   .= "x08x00";            // compression method
            $fr   .= $hexdtime;             // last mod time and date

            // "local file header" segment
            $unc_len = strlen($data);
            $crc     = crc32($data);
            $zdata   = gzcompress($data);
            $c_len   = strlen($zdata);
            $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
            $fr      .= pack('V', $crc);             // crc32
            $fr      .= pack('V', $c_len);           // compressed filesize
            $fr      .= pack('V', $unc_len);         // uncompressed filesize
            $fr      .= pack('v', strlen($name));    // length of filename
            $fr      .= pack('v', 0);                // extra field length
            $fr      .= $name;

            // "file data" segment
            $fr .= $zdata;

            // "data descriptor" segment (optional but necessary if archive is not
            // served as file)
            $fr .= pack('V', $crc);                 // crc32
            $fr .= pack('V', $c_len);               // compressed filesize
            $fr .= pack('V', $unc_len);             // uncompressed filesize

            // add this entry to array
            $this -> datasec[] = $fr;
            $new_offset        = strlen(implode('', $this->datasec));

            // now add to central directory record
            $cdrec = "x50x4bx01x02";
            $cdrec .= "x00x00";                // version made by
            $cdrec .= "x14x00";                // version needed to extract
            $cdrec .= "x00x00";                // gen purpose bit flag
            $cdrec .= "x08x00";                // compression method
            $cdrec .= $hexdtime;                 // last mod time & date
            $cdrec .= pack('V', $crc);           // crc32
            $cdrec .= pack('V', $c_len);         // compressed filesize
            $cdrec .= pack('V', $unc_len);       // uncompressed filesize
            $cdrec .= pack('v', strlen($name) ); // length of filename
            $cdrec .= pack('v', 0 );             // extra field length
            $cdrec .= pack('v', 0 );             // file comment length
            $cdrec .= pack('v', 0 );             // disk number start
            $cdrec .= pack('v', 0 );             // internal file attributes
            $cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set

            $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
            $this -> old_offset = $new_offset;

            $cdrec .= $name;

            // optional extra field, file comment goes here
            // save to central directory
            $this -> ctrl_dir[] = $cdrec;
        }
        function filezip(){
            $data    = implode('', $this -> datasec);
            $ctrldir = implode('', $this -> ctrl_dir);

            return
                $data .
                $ctrldir .
                $this -> eof_ctrl_dir .
                pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
                pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
                pack('V', strlen($ctrldir)) .           // size of central dir
                pack('V', strlen($data)) .              // offset to start of central dir
                "x00x00";                             // .zip file comment length
        }
    }

    三    执行外部命令

              ①   exec("tar -zxvf xxx.tar.gz");

              ②   system("tar -zxvf xxx.tar.gz")

              ③   $obj=new com("wscript.shell");//加载组件 获得解压
                     $obj->run("winrar x $dir".$name." ".$dir ,1,true);//上传解压文件
                     // unlink($dir.$name);//删除文件


     

    相信你把上面所有的方法尝试一遍之后你肯定对php有一个新的认知;在此之前我网络上查过相应的资料但是都很单一

    当让他们的方法都能够解决我日常开发中问题;;但是总觉的缺点什么所以抽时间好好的‘研究’了一下,果然这里面有很多值得探讨的东西

    今天把自己的所知写在这里希望对大家有所以帮助

  • 相关阅读:
    signalr推送消息
    WebApi2跨域问题
    iTextSharp生成pdf的一个简单例子
    遇到的错误记录
    AutoMapper用法
    visual studio 2015中的webapi生成helpPage,页面不显示方法说明问题解决
    visualstudio 2013 mysql entityframework :实体模型无法添加,闪退
    webapi相关知识
    2016年4月14日
    2016年4月13日
  • 原文地址:https://www.cnblogs.com/php-blog/p/3402279.html
Copyright © 2011-2022 走看看