代码之家  ›  专栏  ›  技术社区  ›  Igor Savinkin

使用php在服务器上解压缩zip存档

  •  0
  • Igor Savinkin  · 技术社区  · 9 年前

    我尝试了一些用php自动解压文件的方法,但都失败了:

    第一种变体

    <?php
    function unzip($file){
      $zip=zip_open(realpath(".")."/".$file);
      if(!$zip) {return("Unable to proccess file '{$file}'");}
      $e='';
    
      while($zip_entry=zip_read($zip)) {
       $zdir=dirname(zip_entry_name($zip_entry));
       $zname=zip_entry_name($zip_entry);
    
       if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'"; continue; }
       if(!is_dir($zdir)) mkdirr($zdir,0777);
    
       #print "{$zdir} | {$zname} \n";
    
       $zip_fs=zip_entry_filesize($zip_entry);
       if(empty($zip_fs)) continue;
    
       $zz=zip_entry_read($zip_entry,$zip_fs);
    
       $z=fopen($zname,"w");
       fwrite($z,$zz);
       fclose($z);
       zip_entry_close($zip_entry);
    
       } 
    zip_close($zip);
    
    return $e;
    } 
    $file = 'file_name.zip';
    echo unzip($file);
    

    第二种变体

    <?php
    $zip = zip_open("my_linkedin_groups_scrape_my_run_1_2015.zip");
    if ($zip) {
    while ($zip_entry = zip_read($zip)) {
      $fp = fopen("./".zip_entry_name($zip_entry), "w");
      if (zip_entry_open($zip, $zip_entry, "r")) {
        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
        fwrite($fp,"$buf");
        zip_entry_close($zip_entry);
       fclose($fp);
      }
     }
     zip_close($zip);
    }
    ?>
    

    第三种变体

    <?php 
    // assuming file.zip is in the same directory as the executing script.
    $file = 'file.zip';
    
    // get the absolute path to $file
    $path = pathinfo(realpath($file), PATHINFO_DIRNAME);
    
    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
      // extract it to the path we determined above
      $zip->extractTo($path);
      $zip->close();
      echo "WOOT! $file extracted to $path";
    } else {
      echo "Doh! I couldn't open $file";
    }
    ?>
    

    对于第三种情况,输出为 Doh! I couldn't open file.zip

    发生了什么?我缺什么了吗? 我

    2 回复  |  直到 9 年前
        1
  •  1
  •   Arjuna Wenzel    9 年前

    写/读权限似乎有问题。
    将测试权限更改为0777

        2
  •  0
  •   shamot joshi    9 年前

    我会选择第三种变体。尝试使用zip文件的绝对路径,并在错误消息中转储$res。它会准确地指出错误,只需将其与特定的错误代码进行比较 http://php.net/manual/en/ziparchive.open.php .