簡體   English   中英

如何在CodeIgniter中使用表單數據上傳和驗證圖像?

[英]How to upload and Validate Image with Form Data in CodeIgniter?

問題是如何同時驗證圖像和表單數據

$this->load->library('form_validation');
$this->form_validation->set_message('file_check', 'jpg attachement allowed Only');
$this->form_validation->set_rules('file', '', 'callback_file_check');
$this->form_validation->set_rules('number','Number','trim|required|min_length[10]|max_length[10]');

if($this->form_validation->run()){
    $name=$this->input->post('name');
    $subject=$this->input->post('subject');
    $messege=$this->input->post('messege');
    $number=$this->input->post('number');

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

    //upload file to directory
    if($this->upload->do_upload('file') ){
        $upload_data = $this->upload->data();
        $this->load->library('email',$config);
        $this->email->attach($upload_data['full_path']);
        $this->email->set_newline("\r\n");
        $email_body ="<div >".$messege."</div>";
        $this->email->set_mailtype("html");
        $this->email->from('mail@gmail.com',$name);
        $this->email->to('mailto@gmail.com');
        $this->email->subject($subject);
        $this->email->message($email_body);
        $this->email->send();
        $this->index();
    }
}    

您可以使用自定義驗證功能來實現。

function do_upload()
{
  $this->load->library('form_validation'); 
  $this->form_validation->set_rules('file', 'File', 'callback_file_check'); 
  $this->form_validation->set_rules('number','Number','trim|required|min_length[10]|max_length[10]');
  if($this->form_validation->run()==TRUE)
  {
    //upload image
  }
  else
  {
    // return form error
  }
}

function file_check($str){
  // load file helper 
  $this->load->helper('file');
  // image mime type
  $allowed_mime_type_arr = array('image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
  $mime = get_mime_by_extension($_FILES['file']['name']);
  // file is uploaded and not empty
  if(isset($_FILES['file']['name']) && $_FILES['file']['name']!="")
  {
    if(in_array($mime, $allowed_mime_type_arr))
    {
      return TRUE;
    }
    else
    {
      // return false with custome error message
      $this->form_validation->set_message('file_check', 'Please select only gif/jpg/png file.');
      return FALSE;
    }
  }
  else
  {

    $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
    return FALSE;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM