codeigniter中的图像验证

时间:2015-07-30 06:22:07

标签: php codeigniter

我正在尝试在以下代码中验证表单。

控制器:

public function do_register()
{
    $this->load->library('form_validation');

    $this->form_validation->set_rules('uname', 'Username', 'required|min_length[4]|max_length[15]');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('pass', 'Password', 'required|min_length[4]');
    $this->form_validation->set_rules('address', 'Details', 'required|min_length[4]');
    if($this->form_validation->run() == FALSE)
    {
        $this->load->view('login_view');
    }
    else
    {
        $path = $_FILES['image']['name'];
        $imgext=strtolower(strrchr($path,'.'));
        $imgname= $this->generateRandomString().$imgext;
        if($path!='')
        {
            $im= $this->config->item('base_url').'/uploads'.'/'.$imgname;
            $x=$this->do_upload($imgname);
            $data['img']=$im;
        }

        $this->search_model->register_user($data['img']);
        $this->load->view('register_view'); 
    }
}   
function generateRandomString()
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < 8; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}   
function do_upload($img)
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';

    $config['max_size'] = '1024 ';

    $config['file_name'] = $img;
    $this->load->library('upload',$config);

    if ( ! $this->upload->do_upload('image'))

    {
        $error = array('error' => $this->upload->display_errors()); 
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());
        return $data;
    }
    return;
}

如果我离开图片区域并进行注册,那么我收到了错误

  

错误号:1048未定义的变量数据和列'img'不能为空。

我认为验证在图像字段的情况下不起作用?如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这里你得到的数据库错误不是PHP错误所以为了在PHP端验证你的图像字段,你可以把它检查为

if($_FILES['image']['error'] != 4){
   // then insert or upload will be done
}else{
   // please select an image
}

答案 1 :(得分:1)

    if (empty($_FILES['image']['name'])) 
    {
    //User did not uploaded file. Use default image 
    }
    else
    {
    //User uploaded the file. Do something
    }