How To Implement Multiple Image Uploading With View, Edit And Delete In CodeIgniter?

Today, We want to share with you multiple image upload in codeigniter.In this post we will show you upload multiple images in codeigniter using ajax, hear for how to upload 2 separate images in codeigniter we will give you demo and example for implement.In this post, we will learn about How To Upload Multiple Images In Codeigniter? with an example.

Upload Multiple Files and Images in CodeIgniter

Step 1: Html Part

using Html code

<input type="file" name="profilePic[]" multiple="multiple">

Step 2: PHP Code

<?php
public function profiles()
{       
    $this->load->library('upload');
    $dataInfo = array();
    $profiles = $_FILES;
    $cpt = count($_FILES['profilePic']['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES['profilePic']['name']= $profiles['profilePic']['name'][$i];
        $_FILES['profilePic']['type']= $profiles['profilePic']['type'][$i];
        $_FILES['profilePic']['tmp_name']= $profiles['profilePic']['tmp_name'][$i];
        $_FILES['profilePic']['error']= $profiles['profilePic']['error'][$i];
        $_FILES['profilePic']['size']= $profiles['profilePic']['size'][$i];    

        $this->upload->initialize($this->set_upload_options());
        $this->upload->do_upload();
        $dataInfo[] = $this->upload->data();
    }

    $data = array(
        'name' => $this->input->post('pd_name'),
        'prod_image' => $dataInfo[0]['file_name'],
        'prod_image1' => $dataInfo[1]['file_name'],
        'prod_image2' => $dataInfo[2]['file_name'],
        'created_time' => date('Y-m-d H:i:s')
     );
     $result_set = $this->tbl_profiles_model->insertUser($data);
}

private function set_upload_options()
{   
    //upload an image options
    $config = array();
    $config['upload_path'] = './resources/images/profiles/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE;

    return $config;
}
?>

Multiple Image Upload in CodeIgniter with Example

Create MySQL Database Table

CREATE TABLE IF NOT EXISTS `profiles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Create Directory To Upload Files
make directory uploads/profiles in the root folder

Read Also:  Laravel 5.7 Queues Send Mail Tutorial With Example

Create Controller For Files Upload
make controller Files_Upload.php in application/controllers

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_Upload extends CI_Controller {
    function  __construct() {
        parent::__construct();
        $this->load->model('profiles');
    }    
    function index(){ 
        $data = array();
        if($this->input->post('submitForm') && !empty($_FILES['store_profiles']['name'])){
            $profilesCount = count($_FILES['store_profiles']['name']);
            for($i = 0; $i < $profilesCount; $i++){ $_FILES['upload_File']['name'] = $_FILES['store_profiles']['name'][$i]; $_FILES['upload_File']['type'] = $_FILES['store_profiles']['type'][$i]; $_FILES['upload_File']['tmp_name'] = $_FILES['store_profiles']['tmp_name'][$i]; $_FILES['upload_File']['error'] = $_FILES['store_profiles']['error'][$i]; $_FILES['upload_File']['size'] = $_FILES['store_profiles']['size'][$i]; $uploadPath = 'uploads/profiles/'; $config['upload_path'] = $uploadPath; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if($this->upload->do_upload('upload_File')){
                    $fileData = $this->upload->data();
                    $dpStoreImg[$i]['file_name'] = $fileData['file_name'];
                    $dpStoreImg[$i]['created'] = date("Y-m-d H:i:s");
                    $dpStoreImg[$i]['modified'] = date("Y-m-d H:i:s");
                }
            }            
            if(!empty($dpStoreImg)){
                //Insert file information into the database
                $insert = $this->profiles->insert($dpStoreImg);
                $isActiveMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                $this->session->set_flashdata('isActiveMsg',$isActiveMsg);
            }
        }
        //Get profiles data from database
        $data['profiles'] = $this->profiles->getRows();
        //Pass the profiles data to view
        $this->load->view('profiles_upload/index', $data);
    }
}

Create Files Model
make Files.php model in application/models

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Files extends CI_Model {
    public function getRows($id = ''){
        $this->db->select('id,file_name,created');
        $this->db->from('profiles');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('created','desc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }    
    public function insert($data = array()){
        $insert = $this->db->insert_batch('profiles',$data);
        return $insert?true:false;
    }    
}

Create Upload Files Views
make profiles_upload/index.php in application/views

<div class="container">
	<div class="row ">			
		<form enctype="multipart/form-data" action="" method="post">
		<div class="form-group  col-sm-3">
			<label>Choose Files</label>
			<input type="file" class="form-control" name="store_profiles[]" multiple/>				
		</div>   
		<div class="form-group  col-sm-6">		
			<input  type="submit" class="btn btn-default" name="submitForm" id="submitForm"/>	
		</div>		
	</div> 	
	<div class="row ">
		<p><?php echo $this->session->flashdata('isActiveMsg'); ?></p>
	</div>
    <div class="row">
		<div class="profiles">
			<ul>
				<?php if(!empty($profiles)): foreach($profiles as $file): ?>
				<li>
					<img src="<?php echo base_url('uploads/profiles/'.$file['file_name']); ?>" alt="" >
					<p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
				</li>
				<?php endforeach; else: ?>
				<p>No File uploaded.....</p>
				<?php endif; ?>
			</ul>
		</div>
    </div>
</div>

Configure Auto-load

$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url');

I hope you get an idea about how to upload two different files in codeigniter.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.