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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.