codeIgniter form validation not working with file upload option

1.1k Views Asked by At

I am trying this code but it is not working with file upload. When there is no file uploading field it works fine but with file upload its not working.

Please help me.

form.php

<?php echo validation_errors(); ?>  

<?php echo form_open_multipart('emp'); ?>

    <form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data"> 
        <table border="1">
            <tr> 
                <th>Name</th> 
                <td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td> 
            </tr> 
            <tr> 
                <th>Email </th> 
                <td><input type="text" name="email" value="<?php echo $email; ?>"/></td> 
            </tr> 
            <tr> 
                <th>Address</th> 
                <td><input type="text" name="address" value="<?php echo $address; ?>" /></td> 
            </tr> 
            <tr> 
                <th>Phone</th> 
                <td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td> 
            </tr>
            <tr> 
                <th>Photo</th> 
                <td><input type="file" name="userfile" /></td> 
            </tr>              
        </table>
        <input type="hidden" name="id" value="<?php echo $id; ?>" /> 
        <input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/> 
        <input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/> 
    </form> 
</body> 

Here is the controller code. Emp.php

  public function index(){
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name','required','callback_username_check');
        $this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
        $this->form_validation->set_rules('address', 'Address', 'required');
        $this->form_validation->set_rules('phone', 'Phone', 'required');
        if (empty($_FILES['userfile']['name']))
        {
            $this->form_validation->set_rules('userfile', 'Photo', 'required');
        }

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '1800';
        $config['max_width']  = '1924';
        $config['max_height']  = '1924';
        $new_name = time().$_FILES['userfile']['name'];
        $config['file_name'] = $new_name;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
        {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('form', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());           
            $this->emp_model->add_data();
            $query['value']=$this->GetAll(); 
        }
}
2

There are 2 best solutions below

0
Rahul Sati On

try this

if (null != ($_FILES['userfile']['tmp_name']))
{
  $this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}

And this function for validation

public function checkPostedFiles()
    {
        $file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
        $file_name = str_replace(" ", "", $file_name);
         if (isset($_FILES['userfile']) && !empty($file_name)) {
            $allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
            $extension = end(explode(".", $file_name));
            if (in_array($extension, $allowedExts)) {
                 return true;
            } else {
                $this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
                return false;
            }
         } else {
             $this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
             return false;
         }
    }
0
Bugfixer On

Check this sample code for image uploading :

Form :

<form method="post" action="" id="upload_file">
                    <div class="modal-body">
                            <div class="box-body">                                         
                                  <div class="form-group">
                                        <label for="exampleInputFile">Profile Picture</label>
                                        <input type="file" id="userfile" accept="image/*" name="userfile">
                                        <p class="help-block">Requested size : 215*215</p>
                                    </div>

                           </div>        
                    </div>

                    <div class="modal-footer">
                            <div class="btn-group">
                                    <button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>                                       
                                    <input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
                            </div>
                    </div>
                    </form>  

Include this js in your view.

Js for form submission

$(function() {
    $('#upload_file').submit(function(e) {

        e.preventDefault();
        $.ajaxFileUpload({
        url:'<?php echo base_url(); ?>profile/upload_file', 
        type: "POST",
        fileElementId :'userfile',         

        success: function() {
    alert("file uploaded!");
     }
         });
    return false;
    });
});

In controller

$userid = $session_data['id'];

$file_element_name = 'userfile';    

$pathToUpload = '/var/www/html/uploads/' . $userid;

if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);

if (!$create)
return;
}


$config['upload_path']   = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';


$this->load->library('upload', $config);

if (!$this->upload->do_upload($file_element_name))
{

$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(

'userPhoto' => $data['file_name']

);


$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data); 

}
//@unlink($_FILES[$file_element_name]);