Codeigniter Multiple File Upload with image Resizing/thumbnail image Creation - Mostlikers

27 March, 2017

Codeigniter Multiple File Upload with image Resizing/thumbnail image Creation

Codeigniter Multiple File Upload with image Resizing/thumbnail image Creation. The CodeIgniter is a powerful PHP framework it will provide more inbuilt libraries like file upload, email, Session, Cart. Today we are going to see How to upload multiple images and How to resize(thumbs) uploaded the image using Codeigniter Framework.



Live Demo            Download

Why We Need to Create Thumbnails Image

Thumbnails images reduce the web site loading, performance. Example think about your social media profile image upload section. Once you have uploaded the new image the server it will be resized small, Medium, Large size images. 

You can see chat section your image will be the small image at the same time. It won't affect any pixel and resolution of image quality. In case you have uploaded more than 2MB large image file also the script will resize upload with thumbnails.


How to Upload Multiple Images

Follow the below 4 steps for creating a  table, MVC pattern Script
  1. Create a New Gallery table With respective Colum name like (id,user_id, image).
  2. Create a New Folder(uploads) before the application Folder
  3. Create a New Controller name Called 'User' load basic libraries (URL, form, upload) 
  4. Create model name called users get. Write the function to get all the image.
  5. Load and Access the HTML Form Element

Step 1 Create new Gallery table

Create a new table called gallery with a respective column. User_id columns to identify the particular user uploaded images.
CREATE TABLE `gallery` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `image` varchar(250) NOT NULL,
  `update_date` timestamp NOT NULL
)

Step 2 Create upload and thumbs Folder

For storing the image we need to create two folders. The first name as uploads give some standard name so I have mention folder as uploads, here I will store all uploaded images with thumbs folder.

  • codeiginter/uploads/
  • codeiginter/uploads/gallery/
  • codeiginter/uploads/gallery/thumbs/


Step 3 Load the function in Controller

Here I have created 2 functions for load the HTML file the second function to upload the multiple images. Create a new controller class name called users. load the below 2 functions.

File Path : application/controllers/users.php
URL Path: http://project folder/index.php/users/

<?php 
class users extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->model('users_model','users'); 
        // users is users_model alias name        
    }

    public function index()
    {
        $user_id = 1234;
        $this->data['all_image'] = $this->users->get_image($user_id);
        $this->load->view('multiple',$this->data);             

    }

    public function upload_multiple()
    {
        $user_id = 1234; // session or user_id       
        if(isset($_FILES['userfile']) && $_FILES['userfile']['error'] != '4') :
            $files = $_FILES;
            $count = count($_FILES['userfile']['name']); // count element 
            for($i=0; $i<$count; $i++):
                $_FILES['userfile']['name']= $files['userfile']['name'][$i];
                $_FILES['userfile']['type']= $files['userfile']['type'][$i];
                $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
                $_FILES['userfile']['error']= $files['userfile']['error'][$i];
                $_FILES['userfile']['size']= $files['userfile']['size'][$i];
                $config['upload_path'] = './uploads/gallery/';
                $target_path = './uploads/gallery/thumbs/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = '10000'; //limit 1 mb
                $config['remove_spaces'] = true;
                $config['overwrite'] = false;
                $config['max_width'] = '1024';// image max width 
                $config['max_height'] = '768';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                $this->upload->do_upload('userfile');
                $fileName = $_FILES['userfile']['name'];
                $data = array('upload_data' => $this->upload->data()); 
                if(!$this->upload->do_upload('userfile'))
                {
                   $error = array('upload_error' => $this->upload->display_errors());
                   $this->session->set_flashdata('error',  $error['upload_error']); 
                   echo $files['userfile']['name'][$i].' '.$error['upload_error']; exit;

                } // resize code
                $path=$data['upload_data']['full_path'];
                 $q['name']=$data['upload_data']['file_name'];
                 $configi['image_library'] = 'gd2';
                 $configi['source_image']   = $path;
                 $configi['new_image']   = $target_path;
                 $configi['maintain_ratio'] = TRUE;
                 $configi['width']  = 250; // new size
                 $configi['height'] = 250;
                $this->load->library('image_lib');
                $this->image_lib->initialize($configi);    
                $this->image_lib->resize();
                $images[] = $fileName;
                $image_upload = array('user_id' => $user_id,'image' => $fileName);
                $this ->db-> insert ('gallery',$image_upload); 
                         
            endfor;
        endif;
        redirect(site_url('users'));
    }

}


Step 4 Load the modules

Here we are getting all the uploaded image data from the gallery table. $result return particular user data with order by descending.

Path: application/models/users_model.php
<?php
class Users_model extends CI_Model
{
    public function get_image($user_id)
    {
        $sql = "SELECT * FROM gallery WHERE user_id='$user_id' order by id DESC";
        $result = $this->db->query($sql)->result();        
        return $result; 
    }  

}

Step 5 Load the HTML Template to the view Folder

For an uploading the image we need to create an HTML attribute file. Create new HTML file, load with views folder.
Path : application/views/multiple.php
<div class="form_data">
   <form method="post" action="<?php echo site_url('users/upload_multiple')?>" enctype="multipart/form-data">
      <input type="file" multiple="multiple" name="userfile[]">
      <input type="submit" value="Upload image" name="submit">
   </form>
</div>
<!--uploaded Image -->
<?php if(isset($all_image)) : ?>
<table width="50%" cellpadding="1" cellspacing="0">
   <?php foreach ($all_image as $image) : ?>
   <tr>
      <td><img class="img" src="<?=base_url().'uploads/gallery/'.$image->image ?>"></td>
      <td><img class="img" src="<?=base_url().'uploads/gallery/thumbs/'.$image->image ?>"></td>
   </tr>
   <?php endforeach;?>
</table>
<?php endif; ?>
<!-- End upload -->
</div>
<style type="text/css">
   .form_data {
   border-style: dotted;
   padding: 20px;
   margin-bottom: 50px;
   }
   .img {
   max-width: 100%;
   height: auto;
   padding: 4px;
   line-height: 1.42857143;
   background-color: #fff;
   border: 1px solid #ddd;
   border-radius: 4px;
   -webkit-transition: all .2s ease-in-out;
   -o-transition: all .2s ease-in-out;
   transition: all .2s ease-in-out;
   }
</style>






We hope this tutorial helpful for you. If you have any further queries, requests or suggestions comment below box.

3 comments:

  1. Good article. Many users have been facing problem with it.

    ReplyDelete
    Replies
    1. Thanks Man. Don't forget share with friends

      Delete