作者 : Bun Wong
日期 : 2009年03月25日
标签 : PHP CodeIgniter
浏览 : 1380 次
评论 : 5 个
http://www.hdwong.com/article/29/

CodeIgniter Upload Fixing —— 上传任何文件类型

技术交流 @ 2009年03月25日 收藏&分享

昨天下班前遇到了一个很抓狂的东西,本来以为很快搞定的。我用 CodeIgniter Upload Library 上传一些文件,但是我不需要限制这些文件是否符合指定格式(因为这个是管理员后台,都是自己人上传),按照 CodeIgniter 官方文档 的说法,allowed_types 的设置默认是 None 的,当时认为是不去设置 allowed_types 就会接受上传所有类型的文件了,谁知令人烦躁的是居然不设置这个就上传不了文件,把它换成 jpg|png|gif 就好了,但是又只能上传图片类型文件。

今天实在受不了,打开 CodeIgniter 的代码( system/libraries/Upload.php ),用 xdebug 跟踪,到 Line202

// Is the file type allowed to be uploaded?
if ( ! $this->is_allowed_filetype())
{
    $this->set_error('upload_invalid_filetype');
    return FALSE;
}

进入 Line546 的 is_allowed_filetype 成员函数

/**
* Verify that the filetype is allowed
*
* @access public
* @return bool
*/
function is_allowed_filetype()
{
    if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
    {
        $this->set_error('upload_no_file_types');
        return FALSE;
    }
 
    $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
 
    foreach ($this->allowed_types as $val)
    {
        $mime = $this->mimes_types(strtolower($val));
 
        // Images get some additional checks
        if (in_array($val, $image_types))
        {
            if (getimagesize($this->file_temp) === FALSE)
            {
                return FALSE;
            }
        }
 
        if (is_array($mime))
        {
            if (in_array($this->file_type, $mime, TRUE))
            {
                return TRUE;
            }
        }
        else
        {
            if ($mime == $this->file_type)
            {
                return TRUE;
            }
        }
    }
    
    return FALSE;
}

这段代码有个比较搞笑的问题,在 Line566 就是它判断设置了的类型的时候,如果这个 each 里是图片扩展名,那么它就去 getimagesize,如果不是图片,就返回 false,这样做太 BT 了。如果我要上传一个 zip 文件,那么如果 allowed_types = 'jpg|zip',上传就会失败,因为它第一个 each 就去判断是不是 jpg 文件了,如果写成 allowed_type = 'zip|jpg' 才能成功,这个的确很晕……

当然,我们这里要解决的问题是让它能接受任何类型,在 Line554,它判断了如果没有设置 allowed_types 时,它也会返回 false,我们只需要把 Line554 到 Line558 这个代码块改成如下,就可以解决问题了,嘻嘻,够暴力吧。

if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
{
    // $this->set_error('upload_no_file_types');
    // return FALSE;
    return TRUE;
}

评论 (5)

  • #1.

    2009年03月25日

    点广告了

  • #2. 路过

    2009年04月05日

    我也点广告了

  • #3. Bun Wong

    2009年04月05日

    。。。怎么都是来点广告的。。。

  • #4. youyou

    2009年04月10日

    baimingjiushidianguanggao

  • #5. 飞鱼

    2010年02月11日

    恩。这个bug一直都存在。呵呵,代码我都不去看,直接把zip、rar放在前面试了出来。

    嘿嘿,放一个自己博客的链接
    <a>http://www.aifish.net</a>

* 昵称:

* 评论:

* 验证码: (请输入下图的 4 位数字)

Captcha看不请, 换一张

© 2011 Bun Wong

本博客基于 Bun PHP Framework 构建 • 粤ICP备07036370号