提取 Zip 内的目录 [英] Extract Directory Inside Zip

查看:26
本文介绍了提取 Zip 内的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,用于将 zip 存档中的文件提取到脚本所在的目录中.

I'm writing a script to extract files from a zip archive into the directory that the script is located.

这是我的代码:

$zip = new ZipArchive;
if ($zip->open('latest.zip') === TRUE) {
    $zip->extractTo('.');
    $zip->close();
    unlink('installer.php');
    echo 'it works!';
} else {
    echo 'failed';
}

这很好用,但有一个问题.拉链包含一个额外的层.(zip/directory/files) 它像这个目录/文件一样提取,而不仅仅是文件.

This works fine, but there's one problem. The zip contains an extra layer. (zip/directory/files) which extracts like this directory/files rather then just the files.

有没有办法去除这个额外的层?

Is there a way to remove this extra layer?

感谢您的帮助!

乔尔·德雷珀

推荐答案

为了防止任何文件被覆盖,您可能希望先将 zip 文件解压缩到一个目录中.我会创建一个随机名称的目录,将 zip 解压缩到该目录中,然后检查任何子目录:

In order to prevent any files from getting overwritten, you probably want to extract the zip file into a directory first. I'd create a directory with a random name, extract the zip into that director and then check for any subdirectories:

<?php

// Generate random unzip directory to prevent overwriting
// This will generate something like "./unzip<RANDOM SEQUENCE>"
$pathname = './unzip'.time().'/';

if (mkdir($pathname) === TRUE) {

  $zip = new ZipArchive;

  if ($zip->open('latest.zip') === TRUE) {

    $zip->extractTo($pathname);

    // Get subdirectories
    $directories = glob($pathname.'*', GLOB_ONLYDIR);

    if ($directories !== FALSE) {

      foreach($directories as $directory) {

        $dir_handle = opendir($directory);

        while(($filename = readdir($dir_handle)) !== FALSE) {

          // Move all subdirectory contents to "./unzip<RANDOM SEQUENCE>/"
          if (rename($filename, $pathname.basename($filename)) === FALSE) {
            print "Error moving file ($filename) \n";
          }
        }
      }
    }

    // Do whatever you like here, for example:
    unlink($pathname.'installer.php');

  }

  // Clean up your mess by deleting "./unzip<RANDOM SEQUENCE>/"
}

我还没有测试过这段代码,所以,使用风险自负,另外,它在 Windows 系统上可能无法按预期工作.此外,请查看我使用的所有功能的文档:

I haven't tested this code, so, use at your own risk, also, it may not work as intended on Windows systems. Additionally, check out the documentation for all of the functions I used:

这篇关于提取 Zip 内的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆