php zipArchive仅解压缩某些扩展名 [英] php zipArchive unzip only certain extensions

查看:225
本文介绍了php zipArchive仅解压缩某些扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解压缩上传的内容.但是出于安全目的,必须验证文件仅是图像文件,以使某人无法将php添加到zip中,然后再运行它.

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') );

不返回null.有没有可以用于此的参数,或者我必须使用正则表达式遍历zip文件以匹配扩展名并创建文件夹并使用代码保存文件?

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??

谢谢

推荐答案

对于将来需要此解决方案的任何人,这是我的解决方案.感谢Ciro的职位,我只需要稍微扩展一下您的职位.为了确保创建了所有文件夹,我首先为这些文件夹循环,然后进行拉伸.

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

这篇关于php zipArchive仅解压缩某些扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆