【问题标题】:Codeigniter FILE upload validation failureCodeigniter 文件上传验证失败
【发布时间】:2010-11-21 01:29:29
【问题描述】:

我的应用程序在多个控制器中成功使用了 Codeigniter 验证,用于各种输入字段。但是在上传和验证上传的图像时,验证会抱怨。

我有以下表格: require_once('head.php'); 回声'

更新头像

'; 如果(验证错误()) echo ''.validation_errors().'';
if($info)
    echo '<div class="info">'.$info.'</div>';

$attributes = array('class' => 'updateavatarform', 'id' => 'updateavatarform');
echo form_open_multipart('user/avatar', $attributes);

echo '<div>Select Image</div>';
$data = array(
        'name'        => 'avatar',
        'id'          => 'avatar',
        'value'       => '',
        'maxlength'   => '',
        'size'        => '48',
      );
echo form_upload($data);

echo '<br/><br/>';
echo form_submit('submit', 'Submit');
echo form_close();
require_once('footer.php');

控制器看起来像:

function avatar()
{
    $data['user'] = $this->authorize->isLoggedIn();
    if(!$data['user'])
        $this->authorize->protectUser();

    $data['title'] = 'Evcenter User Update Avatar';
    $data['keywords'] = 'alternative fuel';
    $data['description'] = 'evcenter.org';
    $data['info'] = FALSE;

    if($_POST)
    {
            $this->load->model('User_model', '', TRUE);

            $this->load->library('form_validation');
            $input['avatar'] = trim($this->input->post('avatar', TRUE));
            $this->form_validation->set_rules('avatar', 'Avatar', 'trim|required|xss_clean');

            if($this->form_validation->run() == FALSE)
            {
                $this->load->view('avatar', $data);
            }
            else
            {
                $avatar = $this->User_model->getAvatar($data['user']['user_id']);
                $old_avatar = $this->config->item('avatarpath').$avatar['avatar'];
                unset($old_avatar);
                $input['avatar'] = $this->uploadAvatar();
                $input['id'] = $data['user']['user_id'];
                $this->User_model->updateAvatar($input);

                $data['info'] = 'Your avatar has been updated';
                $this->load->view('avatar', $data);
            }
    }
    else
    {
        $this->load->view('avatar', $data);
    }
}

如果上传的图片“需要头像字段”,验证会引发以下错误。不用说 $this->uploadAvatar();从注册控制器调用时有效。

谁能看出有什么问题? 文件上传的验证需要与文本输入不同吗?

【问题讨论】:

    标签: validation file forms codeigniter upload


    【解决方案1】:

    正确,文件需要以不同于文本输入的方式进行验证 - 因为它们是,而不是文本输入!

    来自文档:

    function do_upload()
    {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
    
        $this->load->library('upload', $config);
    
        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
    
            $this->load->view('upload_form', $error);
        }   
        else
        {
            $data = array('upload_data' => $this->upload->data());
    
            $this->load->view('upload_success', $data);
        }
    }   
    

    注意对$this-&gt;upload-&gt;do_upload()$this-&gt;upload-&gt;display_errors()的调用

    在 CI 中上传带有文本字段的内容可能很烦人 (imo),我会先将文件上传到您的控制器中,然后如果成功,则执行其余的 POST 数据并更新您的数据库。

    这样如果以后上传有问题,就不会有无效记录了。

    【讨论】:

      【解决方案2】:

      *假设你已经碰巧有一个 MY_Form_Validation 库来扩展内置的 CodeIgniter 东西。*

      首先

      我添加了一些函数来验证 $_FILE 上传的部分基于此:

      http://devbro.com/testing/ci_form_validation/

      我只是复制了函数,而不是整个文件。我不需要自定义运行或执行方法。只是验证方法。 (我已经有一个自定义项,允许我将 form_validation 配置文件和控制器规则混合在一起。)

      /**
      * tests to see if a required file is uploaded
      * 
      * @param mixed $file
      */
      function file_required($file)
      {
          if($file['size']===0)
          {
              $this->CI->form_validation->set_message('file_required','Uploading a file for %s is required.');
              return FALSE;
          }
          return TRUE;
      }
      
      
      /**
      * tests the file extension for valid file types
      * 
      * @param mixed $file
      * @param mixed $type
      */
      function file_allowed_type($file,$type)
      {
          //is type of format a,b,c,d? -> convert to array
          $exts = explode(',',$type);   
          //is $type array? run self recursively
          if(count($exts)>1)
          {
              foreach($exts as $v)
              {
                  $rc = $this->file_allowed_type($file,$v);
                  if($rc===TRUE)
                  {
                      return TRUE;
                  }
              }
          }
      
          //is type a group type? image, application, word_document, code, zip .... -> load proper array
          $ext_groups = array();
          $ext_groups['image'] = array('jpg','jpeg','gif','png');
          $ext_groups['application'] = array('exe','dll','so','cgi');
          $ext_groups['php_code'] = array('php','php4','php5','inc','phtml');
          $ext_groups['word_document'] = array('rtf','doc','docx');
          $ext_groups['compressed'] = array('zip','gzip','tar','gz');
          $ext_groups['pdf'] = array('pdf');
      
          if(array_key_exists($exts[0],$ext_groups))
          {
              $exts = $ext_groups[$exts[0]];
          }
      
          //get file ext
          $file_ext = strtolower(strrchr($file['name'],'.'));
          $file_ext = substr($file_ext,1);
      
          if(!in_array($file_ext,$exts))
          {
              $this->CI->form_validation->set_message('file_allowed_type',"%s should be $type.");
              return false;        
          }
          else
          {
              return TRUE;
          }
      }
      

      等等等等

      那么

      我将我想要的规则添加到我的 form_validation.php 配置文件中,但我将我的 FILE 输入视为包含在 $_POST 中。当然不是,但我会马上解决这个问题。 不要使用 CodeIgniter 内置的其他类型的验证,仅使用您的 FILE 验证!

      $config = array(
      
                  'form/index' => array(
                      array( 'field'=>'my_upload_file', 'label'=>'File To Upload', 'rules'=>'file_required|file_allowed_type[pdf]'),
                      ...
      

      终于

      在我的控制器中,将 $_FILE['my_upload_file'] 添加到 $_POST 数组中

      if ( isset($_FILES['my_upload_file']) )
      {
           $_POST['my_upload_file'] = $_FILES['my_upload_file'];
      }
      

      我认为最大的警告是如果您使用 $_POST 来填充您的模型或其他操作。我的代码项目专门从 input->post() 中抓取元素,并且我没有对任何事情使用批量分配。如果您确实使用批量分配,我会假设您搞砸了您的假设。

      【讨论】:

        猜你喜欢
        • 2020-06-12
        • 2013-05-02
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 2013-10-08
        • 2013-12-13
        • 1970-01-01
        相关资源
        最近更新 更多