Jump to content

Trying to extract contents of Zip file to a folder


dmikester1

Recommended Posts

I'm trying to extract the contents of a zip file to a folder.  I found the ZipArchive class and followed the examples to get it to work for the most part.  But I want to extract the files in the folder inside the zip file but leave the folder out.  So it should extract just the files to my given destination.  I found this on php.net.

 

If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path = 'zipfile.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, "/your/new/destination/".$fileinfo['basename']);
    }                  
    $zip->close();                  
}

?>

 

For some reason that 'copy' line is not working for me.  Obviosly I've changed the variables in the line to the correct variables.  Can someone help me out.

Thanks

Mike

I see. I'd use this method then.

 

<?php

$zip = new ZipArchive;
$destination = 'extracted/';

$zip->open('file.zip');
for($i = 0; $i < $zip->numFiles; $i++) {
$name = basename($zip->getNameIndex($i));
$data = $zip->getFromIndex($i);
file_put_contents($destination.$name, $data);
}

?>

 

Keep in mind, it will over-write files with the same name, in different folders within the zip file.

You should also wipe $data using unset($data) after the loop.

 

Though I don't know exactly how PHP handles large variables left in memory, I know it's good practise to destroy potentially large variables after use.

 

Perhaps someone with more intricate knowledge could help further.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.