Extract files in a zip to root of a folder?

后端 未结 3 880
一个人的身影
一个人的身影 2020-12-21 11:27

I have a zip file uploaded to server for automated extract.

the zip file construction is like this:

/zip_file.zip/folder1/image1.jpg
/zip_file.zip/fo         


        
3条回答
  •  被撕碎了的回忆
    2020-12-21 11:58

    You can do so by using the zip:// syntax instead of Zip::extractTo as described in the php manual on extractTo().

    You have to match the image file name and then copy it:

    if ($entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'])) {
      copy('zip://' . $file_path . '#' . $entry['name'], '/root_dir/' . md5($entry['name']) . '.jpg');
    }
    

    The above replaces your for loop's if statement and makes your extractTo unnecessary. I used the md5 hash of the original filename to make a unique name. It is extremely unlikely you will have any issues with overwriting files, since hash collisions are rare. Note that this is a bit heavy duty, and instead you could do str_replace('/.', '', $entry['name']) to make a new, unique filename.

    Full solution (modified version of your code):

    open($file_path)) {
      for ($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->statIndex($i);
        // is it an image?
        if ($entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'])) {
          # use hash (more expensive, but can be useful depending on what you're doing
          $new_filename = md5($entry['name']) . '.jpg';
          # or str_replace for cheaper, potentially longer name:
          # $new_filename = str_replace('/.', '', $entry['name']);
          copy('zip://' . $file_path . '#' . $entry['name'], '/myFolder/' . $new_filename);
        }
      }
      $zip->close();
    }
    ?>
    

提交回复
热议问题