Unzip file skipping folder

自闭症网瘾萝莉.ら 提交于 2019-12-24 04:16:12

问题


I am creating a php file that will update my site after pulling it off of BitBucket (Git repo). It downloads a zip file of the entire master or a commit, then unzips it in the website's folder.

The problem I am having is there is a randomly named folder that contains all the files in the zip file.

My zip file's contents is similar:

master.php
    - (bitbucketusername)-(reponame)-(commitnumber)
        - folder1
            - index.php
            - test.php
        - index.php
        - config.php
        - etc...

but how can I "bypass" the "randomly" named folder and extract the contents of the folder to the website's root?

echo "Unzipping update...<br>" . PHP_EOL;
$zip = new ZipArchive;
$res = $zip->open($filename);
if ($res === TRUE) {
    $zip->extractTo('/path/to/www');
    $zip->close();
} else {
    echo 'Error: The zip file could not be opened...<br>' . PHP_EOL;
}

Found a related question here:

Operating with zip file in PHP

But how can I make it get the "randomly" named folder's name?


回答1:


Unzip the files to a tmp directory and then mv the files out from the "randomly" named parent folder to the folder that you want to.

echo "Unzipping update...<br>" . PHP_EOL;
$zip = new ZipArchive;
$res = $zip->open($filename);
if ($res === TRUE) {
    $zip->extractTo('/tmp/unzip');
    $directories = scandir('/tmp/unzip');
    foreach($directories as $directory){
        if($directory!='.' and $directory!='..' ){
            if(is_dir($directory)){
                  // rcopy from http://ben.lobaugh.net/blog/864/php-5-recursively-move-or-copy-files
                  rcopy('/tmp/unzip/'.$directory,'/path/to/www');
                  // rm /tmp/unzip here
            }
    }
} 

    $zip->close();
} else {
    echo 'Error: The zip file could not be opened...<br>' . PHP_EOL;
}


来源:https://stackoverflow.com/questions/21171906/unzip-file-skipping-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!