php zipArchive unzip only certain extensions

前端 未结 2 1396
小蘑菇
小蘑菇 2020-12-18 16:01

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 i

相关标签:
2条回答
  • 2020-12-18 16:27

    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";
    }
    
    0 讨论(0)
  • 2020-12-18 16:46

    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";
            }
    ?>
    
    0 讨论(0)
提交回复
热议问题