Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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/folder1/image2.jpg
/zip_file.zip/folder1/image3.jpg

Currently I have this function to extract all files that have extension of jpg:

$zip = new ZipArchive();
    if( $zip->open($file_path) ){
        $files = array();
        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'] ) ){
                $f_extract = $zip->getNameIndex($i);
                $files[] = $f_extract;
            }
        }
        if ($zip->extractTo($dir_name, $files) === TRUE) {
        } else {
            return FALSE;
        }

        $zip->close();
    }

But by using the function extractTo, it will extract to myFolder as ff:

/myFolder/folder1/image1.jpg
/myFolder/folder1/image2.jpg
/myFolder/folder1/image3.jpg

Is there any way to extract the files in folder1 to the root of myFolder?

Ideal:

/myFolder/image1.jpg
/myFolder/image2.jpg
/myFolder/image3.jpg

PS: incase of conflict file name I only need to not extract or overwrite the file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
752 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use this little code snippet instead. It removes the folder structure in front of the filename for each file so that the whole content of the archive is basically extracted to one folder.

<?php
$path = "zip_file.zip";

$zip = new ZipArchive();
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/myDestFolder/".$fileinfo['basename']);
    }                  
    $zip->close();                  
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...