Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract folder content using ZipArchive

Tags:

php

ziparchive

I have compressed_file.zip on a site with this structure:

zip file

I want to extract all content from version_1.x folder to my root folder:

desired

How can I do that? is possible without recursion?

like image 873
quantme Avatar asked Nov 12 '11 03:11

quantme


1 Answers

It's possible, but you have to read and write the file yourself using ZipArchive::getStream:

$source = 'version_1.x';
$target = '/path/to/target';

$zip = new ZipArchive;
$zip->open('myzip.zip');
for($i=0; $i<$zip->numFiles; $i++) {
    $name = $zip->getNameIndex($i);

    // Skip files not in $source
    if (strpos($name, "{$source}/") !== 0) continue;

    // Determine output filename (removing the $source prefix)
    $file = $target.'/'.substr($name, strlen($source)+1);

    // Create the directories if necessary
    $dir = dirname($file);
    if (!is_dir($dir)) mkdir($dir, 0777, true);

    // Read from Zip and write to disk
    $fpr = $zip->getStream($name);
    $fpw = fopen($file, 'w');
    while ($data = fread($fpr, 1024)) {
        fwrite($fpw, $data);
    }
    fclose($fpr);
    fclose($fpw);
}
like image 199
netcoder Avatar answered Oct 17 '22 07:10

netcoder