2012-07-09 163 views
1

我需要unziping上传的内容。但出于安全考虑,必须验证文件是否只是图像文件,以便有人不能将zip添加到zip中,然后再运行它。php zipArchive只解压缩某些扩展

在进行解压缩时,我需要预先保存文件结构。

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

不返回null。是否有一个参数我可以用于此,或者我必须使用正则表达式来循环遍历zip文件以匹配扩展名并创建文件夹并用代码保存文件?

感谢

+0

不要以为您可以使用* .jpg来包含扩展名。你需要解析每个文件。 – Ciro 2012-07-09 01:05:44

回答

2

的人谁需要这在将来这里是我的解决方案。感谢Ciro的这篇文章,我只需要扩展你的一些。为了确保所有文件夹都已创建,我首先为文件夹循环,然后执行沉淀。

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

php.net,处理.txt文件

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