How to upload multiple image with validation in codeigniter?

by scotty_walker , in category: PHP Frameworks , a year ago

How to upload multiple image with validation in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year ago

@scotty_walker 

To upload multiple images with validation in CodeIgniter, you can follow these steps:

  1. Create a form in your view file to allow users to select multiple images:
1
2
3
4
<form action="upload_images" method="post" enctype="multipart/form-data">
    <input type="file" name="images[]" multiple>
    <input type="submit" value="Upload">
</form>


  1. Create a controller method to handle the image upload and validation:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public function upload_images() {
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = 2048; // 2MB

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

    if (!$this->upload->do_upload('images')) {
        $error = array('error' => $this->upload->display_errors());
        $this->load->view('upload_form', $error);
    } else {
        $data = array('upload_data' => $this->upload->data());
        $this->load->view('upload_success', $data);
    }
}


  1. Create a folder named 'uploads' in your application directory to store the uploaded images.
  2. Add validation rules in your controller method to validate the uploaded images:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
$this->load->library('form_validation');
$this->form_validation->set_rules('images[]', 'Images', 'callback_validate_images');

public function validate_images($images) {
    foreach ($images['name'] as $key => $value) {
        if (!empty($value)) {
            $this->form_validation->set_rules('images['.$key.']', 'Image', 'callback_validate_image['.$key.']');
        }
    }
    return $this->form_validation->run();
}

public function validate_image($image, $key) {
    if ($_FILES['images']['size'][$key] > 2048) {
        $this->form_validation->set_message('validate_image', 'The %s size should be less than 2MB.');
        return false;
    } else {
        return true;
    }
}


  1. Create a view file for success message:
1
<p>Images uploaded successfully!</p>


Now, users can upload multiple images with validation in CodeIgniter by following these steps.

Related Threads:

How to upload image in Codeigniter?
How to upload image in codeigniter?
How to upload multiple images using codeigniter?
How delete file and image after upload from codeigniter??
How to upload zip file in Codeigniter?
How to get validation errors in codeigniter?