Search code examples
phpunzipphp-ziparchive

php zipArchive unzip only certain extensions


I'm in need of unziping uploaded content. But for security purposes must verify the files are only image files so that somebody can't add a php into the zip and then run it later.

While doing the unzip I need to preseverve the file structure as well.

$zip->extractTo($save_path . $file_name, array('*.jpg','*.jpeg','*.png','*.gif') );

doesn't return null. Is there a parameter I can use for this or must I iterate with a loop through the zip file using regex to match extensions and create the folders and save the files with code??

Thanks


Solution

  • for anyone who would need this in the future here is my solution. Thanks Ciro for the post, I only had to extend yours a bit. To make sure all folders are created I loop first for the folders and then do the extarction.

    $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";
    }