Monday, July 9, 2012

using php to unzip only certain extensions while preserving folder structure

I recently asked a question on stackoverflow.com about unzipping only some file types (like images). Or similarly make sure the zip does not contain code that can harm the computer.

As this is not available as filter I had to write it.

For anyone who should need this here is the code:

 
$ZipFileName = dirname(__FILE__)."/test.zip";
$home_folder = dirname(__FILE__)."/unziped";

mkdir($home_folder);

$zip = new ZipArchive;
if ($zip->open($ZipFileName ) === true) 
{

    //make all the folders
    for($i = 0; $i < $zip->numFiles; $i++) 
    { 
        $OnlyFileName = $zip->getNameIndex($i);
        $FullFileName = $zip->statIndex($i);    
        if ($FullFileName['name'][strlen($FullFileName['name'])-1] =="/")
        {
            @mkdir($home_folder."/".$FullFileName['name'],0700,true);
        }
    }

    //unzip into the folders
    for($i = 0; $i < $zip->numFiles; $i++) 
    { 
        $OnlyFileName = $zip->getNameIndex($i);
        $FullFileName = $zip->statIndex($i);    

        if (!($FullFileName['name'][strlen($FullFileName['name'])-1] =="/"))
        {
            if (preg_match('#\.(jpg|jpeg|gif|png)$#i', $OnlyFileName))
            {
                copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".$FullFileName['name'] ); 
            } 
        }
    }
    $zip->close();
} else
{
    echo "Error: Can't open zip file";
}

If you need to flatten the zip file remove the part making the folders, and change the copy function using basename to this:

copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".basename($FullFileName['name'])); 

No comments:

Post a Comment