简体   繁体   中英

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

from php.net , handling .txt files

<?php 
   $value="test.zip"; 
   $filename="zip_files/$value"; 
   $zip = new ZipArchive;
     if ($zip->open($filename) === true) {
      echo "Generating TEXT file.";
          for($i = 0; $i < $zip->numFiles; $i++) { 
             $entry = $zip->getNameIndex($i);
               if(preg_match('#\.(txt)$#i', $entry))
                {
                ////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
                 copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt'); 
                } 
              }  
             $zip->close();
            }
    else{
         echo "ZIP archive failed";
        }
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM