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

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

php - Extract files in a zip to root of a folder?

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

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

1 Answer

0 votes
by (71.8m points)

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();                  
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...