codeigniter中的图像验证

时间:2015-07-29 10:33:55

标签: php codeigniter

这段代码足以验证图像吗?请为此提供解决方案?

 $this->load->library('form_validation');
 $rules = array(array('field'=>'image','label'=>'Image','rules'=>'required'));

1 个答案:

答案 0 :(得分:1)

您可以使用image librarycallback function

来验证图片

  function __construct()
  {
    parent::__construct();
    $this->load->helper(array('form', 'html', 'file'));// call form valifation
    $this->load->library('form_validation');// call image library

    $config['upload_path']   = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $this->load->library('upload', $config);

    // some validation configurations ...

    // register a custom callback for the image element
    $this->form_validation->set_rules('image', 'Image', 'callback_handle_upload');
  }

  function index()
  {
    if ($this->form_validation->run() == FALSE)
    {
      $this->load->view('form');
    }
    else
    {
      $this->load->view('success');
    }
  }

  function handle_upload()
  {
    if (isset($_FILES['image']) && !empty($_FILES['image']['name']))
      {
      if ($this->upload->do_upload('image'))
      {
        // set a $_POST value for 'image' that we can use later
        $upload_data    = $this->upload->data();
        $_POST['image'] = $upload_data['file_name'];
        return true;
      }
      else
      {
        // possibly do some clean up ... then throw an error
        $this->form_validation->set_message('handle_upload', $this->upload->display_errors());
        return false;
      }
    }
    else
    {
      // throw an error because nothing was uploaded
      $this->form_validation->set_message('handle_upload', "You must upload an image!");
      return false;
    }
  }