Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload Validation In Codeigniter

I am trying to validate file upload for image uploading, but it is not getting the validation like other fields. I am using Form_Validation.php process for validation.

Image uploading array:

array(
            'field'=>'image',
            'label' => 'Image',
            'rules' => 'required'
        )

when i try to upload the image it did not response like it is required etc. I also want to validate it for .jpg etc and "how to set the file value on incorrect file like instead of .jpg we try to upload the .pdf" like we set the value of input field set_value('field name') etc.

I checked a lot of questions and also try to use call method, but did not able to fix it.

UPDATE:

Please provide detail answer with code example. Please use the form_validation.php way in example and also provide the callback example code, so i can read / learn and modify it accordingly.

UPDATE 2:

 public function Task()
    {
        if ($this->form_validation->run('Sub_Admin/task') == FALSE) {
            $this->data['Task'] = $this->bm->get_usr();
            $data['title'] = "Add New Task";
            $this->load->view('Subadmin/header',$data);
            $this->load->view('Subadmin/nav');
            $this->load->view('Subadmin/sidebar');
            $this->load->view('Subadmin/task', $this->data);
            $this->load->view('Subadmin/footer');
        }
        else
        {

            $config['upload_path'] = './taskimages/'; //The path where the image will be save
            $config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
            $config['max_size'] ='10048'; //The max size of the image in kb's
            //$config['max_width']  = '1024'; //The max of the images width in px
            //$config['max_height']  = '768'; //The max of the images height in px
            $config['overwrite'] = FALSE; //If exists an image with the same name it will overwrite. Set to false if don't want to overwrite
            $this->load->library('upload', $config); //Load the upload CI library
            $this->load->initialize($config);
            $this->upload->do_upload('task');
            $file_info = $this->upload->data();
            $file_name = $file_info['file_name'];
            $data = array(
                'Job_Title' => $this->input->post('jtitle'),
                'Priority' => $this->input->post('jnature'),
                'Assignee' => $this->input->post('assigne'),
                'Employee_Name' => $this->input->post('assignto'),
                'Due_Date' => $this->input->post('ddate'),
                'Reminder' => $this->input->post('reminder'),
                'Task_Image' => $file_name,
            );

            $this->bm->add_task($data);

        }
    }

I am already using CI uploading class but it is not working, and now i want to validate the image/ file from form_validation side.

like image 268
msz Avatar asked Aug 06 '17 17:08

msz


4 Answers

I wrote a complete example for your problem, I hope it will help. In the following code I am using CI's Form validation callback and Form Validation Custom Error Messages.

Controller: Front.php

class Front extends CI_Controller {

public function index() {
    $this->load->view('form');
}

public function upload_image() {
    $this->load->library('form_validation');
    if ($this->form_validation->run('user_data') == FALSE) {
        $this->load->view('form');
    }
    else {
        echo 'You form Submitted Successfully ';
    }
}

public function validate_image() {
    $check = TRUE;
    if ((!isset($_FILES['my_image'])) || $_FILES['my_image']['size'] == 0) {
        $this->form_validation->set_message('validate_image', 'The {field} field is required');
        $check = FALSE;
    }
    else if (isset($_FILES['my_image']) && $_FILES['my_image']['size'] != 0) {
        $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG");
        $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
        $extension = pathinfo($_FILES["my_image"]["name"], PATHINFO_EXTENSION);
        $detectedType = exif_imagetype($_FILES['my_image']['tmp_name']);
        $type = $_FILES['my_image']['type'];
        if (!in_array($detectedType, $allowedTypes)) {
            $this->form_validation->set_message('validate_image', 'Invalid Image Content!');
            $check = FALSE;
        }
        if(filesize($_FILES['my_image']['tmp_name']) > 2000000) {
            $this->form_validation->set_message('validate_image', 'The Image file size shoud not exceed 20MB!');
            $check = FALSE;
        }
        if(!in_array($extension, $allowedExts)) {
            $this->form_validation->set_message('validate_image', "Invalid file extension {$extension}");
            $check = FALSE;
        }
    }
    return $check;
}

}

View: form.php

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload</title>
</head>
<body>
    <h1><a href="<?= base_url() ?>">Form</a></h1>
    <?php if(!empty(validation_errors())): ?>
        <p><?= validation_errors() ?></p>
    <?php endif; ?>
    <?= form_open('front/upload_image', ['enctype' => "multipart/form-data"]) ?>
    <label>Name: </label><input type="text" name="name" value="<?= set_value('name') ?>"></label>
    <label>E-mail: </label><input type="email" name="email" value="<?= set_value('email') ?>"></label>
    <input type="file" name="my_image">
    <button type="submit">Submit</button>
    <?= form_close() ?>
</body>
</html>

form_validation.php

$config = array(
        'user_data' => array(
                array(
                        'field' => 'name',
                        'label' => 'Name',
                        'rules' => 'trim|required'
                ),
                array(
                        'field' => 'email',
                        'label' => 'Email',
                        'rules' => 'trim|required|valid_email'
                ),
                array(
                        'field' => 'my_image',
                        'label' => 'Image',
                        'rules' => 'callback_validate_image'
                )
        )
);

In above example first I am validating the name and email and for the Image I am calling the validate_image function to validate it, since form_validation library does not provide image validation but i has callbacks to do custom validations, the validate_image will check image content type then check image file size and then check image extension if any of these requirements are not fulfilled it will set error message for each requirement using set_message() function of form_validation library.

like image 192
Muhammad Avatar answered Sep 24 '22 23:09

Muhammad


Currently you are not getting error because you set validation rules, you also initialized configuration but after uploading class you are not checking that either file is being uploaded or errors.

Please check below mentioned solution, it will help you fix this.

Update 1 :

In order to call a specific group, you will pass its name to the $this->form_validation->run('task') method. I can not see any $config['task'] array in your code. Please check my below mentioned code and update based on your inputs.

public function Task() {

    $config = array(
        'task' => array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'required'
            ),
            array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required'
            )
    ));
    $this->load->library('form_validation');
    if ($this->form_validation->run('task') == FALSE) {
        $this->data['Task'] = $this->bm->get_usr();
        $data['title'] = "Add New Task";
        $this->load->view('Subadmin/header', $data);
        $this->load->view('Subadmin/nav');
        $this->load->view('Subadmin/sidebar');
        $this->load->view('Subadmin/task', $this->data);
        $this->load->view('Subadmin/footer');
    } else {
        $fconfig['upload_path'] = './taskimages/';
        $fconfig['allowed_types'] = 'gif|jpg|png';
        $fconfig['max_size'] = '10048';
        $fconfig['overwrite'] = FALSE;

        $this->load->library('upload', $fconfig); //Load the upload CI library
        $this->load->initialize($fconfig);

        if (!$this->upload->do_upload('my_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('form' ,$error);
        } else {
            $file_info = $this->upload->data();
            $file_name = $file_info['my_image'];
            $data = array(
                'Job_Title' => $this->input->post('jtitle'),
                'Priority' => $this->input->post('jnature'),
                'Assignee' => $this->input->post('assigne'),
                'Employee_Name' => $this->input->post('assignto'),
                'Due_Date' => $this->input->post('ddate'),
                'Reminder' => $this->input->post('reminder'),
                'Task_Image' => $file_name,
            );

            $this->bm->add_task($data);

            $data['upload_data'] = array('upload_data' => $this->upload->data());
            $this->load->view('YOUR_SUCCESS_VIEW PAGE', $data);
        }
    }
}

Let me know if it not works.

like image 29
Shyam Shingadiya Avatar answered Sep 22 '22 23:09

Shyam Shingadiya


How about File Uploading Class from CI?

Validations are also available from the class:

$config['allowed_types']        = 'gif|jpg|png';
$config['max_size']             = 100;
$config['max_width']            = 1024;
$config['max_height']           = 768;

The link includes the Upload form, Success page and the Controller.

Just follow the instructions from there and you'll never get lost.

like image 44
Jorz Avatar answered Sep 22 '22 23:09

Jorz


I am using this code for multiple images upload. Now try below code, Hope it will help.

 public function __construct(){
        parent::__construct();

        $this->load->helper('date');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->library('form_validation');
        $this->load->library('email');
        $this->form_validation->set_error_delimiters('', '');
        $config['allowed_types'] = 'jpeg|jpg|png|bmp';
        $this->load->library('upload', $config);
        $this->load->library('session');

    }



 public function Task() {
        if ($this->form_validation->run('Sub_Admin/task') == FALSE) {
            $this->data['Task'] = $this->bm->get_usr();
            $data['title'] = "Add New Task";
            $this->load->view('Subadmin/header',$data);
            $this->load->view('Subadmin/nav');
            $this->load->view('Subadmin/sidebar');
            $this->load->view('Subadmin/task', $this->data);
            $this->load->view('Subadmin/footer');
        } else {

            $filesCount = count($_FILES['file']['name']);
            $result     = '';
            if($filesCount > 0) {
                $event_id     = trim($this->input->post('event_name'));
                for($i = 0; $i < $filesCount; $i++) {

                    $_FILES['gallery']['name']      = $_FILES['file']['name'][$i];
                    $_FILES['gallery']['type']      = $_FILES['file']['type'][$i];
                    $_FILES['gallery']['tmp_name']  = $_FILES['file']['tmp_name'][$i];
                    $_FILES['gallery']['error']     = $_FILES['file']['error'][$i];
                    $_FILES['gallery']['size']      = $_FILES['file']['size'][$i];

                    $image = $_FILES['gallery']['name'];
                    $directoryPath = date('Y/M/');

                    $path_info = pathinfo($image);
                    //check file type valid or not
                    if(in_array($path_info['extension'], array('jpg', 'jpeg','png', 'gif','JPG','JPEG'))){
                        // Upload job picture
                        $random = time();
                        $config['upload_path']   = './taskimages/';
                        $config['allowed_types'] = 'jpg|png|jpeg|bmp';
                        $config['file_name']     = $random;
                        $config['encrypt_name']  = TRUE;
                        $config['max_size']      = '250000000';
                        $config['max_width']     = '75000000';
                        $config['max_height']    = '7500000';

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

                        ini_set('upload_max_filesize', '10M');
                        ini_set('memory_limit', '-1');

                        if ($this->upload->do_upload('gallery')) {

                            $imageArray = $this->upload->data();
                            $image_name = $imageArray['raw_name'] . '' . $imageArray['file_ext']; // Job Attachment

                            $config1['image_library'] = 'gd2';
                            $config1['source_image'] = './taskimages/' . $image_name;
                            $config1['create_thumb'] = TRUE;
                            $config1['maintain_ratio'] = TRUE;
                            $config1['width'] = 620;
                            $config1['height'] = 540;

                            $this->load->library('image_lib', $config);
                            $this->image_lib->initialize($config1);
                            $this->image_lib->resize();
                            $this->image_lib->clear();


                            $file_name = $image_name_thumb = $imageArray['raw_name'] . '_thumb' . $imageArray['file_ext'];
                            $data = array(
                                'Job_Title' => $this->input->post('jtitle'),
                                'Priority' => $this->input->post('jnature'),
                                'Assignee' => $this->input->post('assigne'),
                                'Employee_Name' => $this->input->post('assignto'),
                                'Due_Date' => $this->input->post('ddate'),
                                'Reminder' => $this->input->post('reminder'),
                                'Task_Image' => $file_name,
                            );

                            $this->bm->add_task($data);
                        }
                    }
                }
            }
        }
    }
like image 34
er.irfankhan11 Avatar answered Sep 25 '22 23:09

er.irfankhan11