How are you guys? I think you are doing well. TechPool is here with another Codeigniter article today. When you are surfing on web, specially blogs, you can see images with those posts. The structure/layout is same in all the articles. But images and the content is different. How to do it? Here, the person who is uploading posts is having an interface to upload article. For blog posts, images are really important to give the idea in an attractive way. It's bit hard work to do if you don't know the configurations. Many people fail to accomplish this task as I have seen on web. So, I tried a 100% working version of uploading images using Codeigniter. I thought to share it with you through my Blog...


Let's Go!

First download Codeigniter and create a project folder in your localhost(htdocs or www folder). In my case its name is CI_Image_Upload. Then move the Codeigniter files into the project folder. Go to phpMyadmin and create a new database called ci_image. Then cretaew a new table called image_data. SQL code for it;

CREATE TABLE `image_data` (
  `image_id` int(5) NOT NULL AUTO_INCREMENT,
  `image_name` varchar(100) NOT NULL,
  `image` varchar(100) NOT NULL,
    PRIMARY KEY(`image_id`)


Next thing you have to do is making essential configurations for CI project.

Project folder => CI_Image_Upload
Base URL => $config['base_url'] = 'http://localhost/CI_Image_Upload/
Database name => ci_image
Database table name => image_data
Autoload libraries => database
Autoload helpers => form , url, file
Default Controller => Image

Important : 
file helper must be loaded. Otherwise files can not be uploaded!

In my project folder, I use these files.
image_upload.php    -  to load the view for uploading images
image_view.php        -  to load the view for displaying uploaded images
Image.php                 -  controller to handle images
Image_model.phpp  -  to fetch image data from database

First I will create image_upload view file to include the input fields to input images

image_upload.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Image upload</title>
  <!-- Bootstrap CSS link -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2 class="text-center" style="margin-top: 50px;">CodeIgniter Image Upload</h2>
    <br><br>
    <div class="row">
      <div class="col-lg-3"></div>
      <div class="col-lg-6">
      <!-- success message to display after uploading image -->
          <?php if ($this->session->flashdata('success')) {?>
              <div class="alert alert-success alert-dismissible" role="alert">
                  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
                  <?php echo $this->session->flashdata('success'); ?>
              </div>
          <?php  } ?> 
          <!-- validation message to display after form is submitted -->
             <?php echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert">
                     <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                     <span aria-hidden="true">&times;</span></button>','</div>');
             ?>    
             <!-- image upload form      -->
             <?php echo form_open_multipart('Image/add_image') ?>
               <div class="form-group">
                 <label>Image Name</label>
                   <input type="text" class="form-control" id="image_name" name="image_name">
                 </div>
               <div class="form-group">
                 <label>Image</label>
                   <input type="file" class="form-control" id="userfile" name="userfile">
                 </div>
               <input type="submit" class="btn btn-primary" value="Upload">
             <?php form_close() ?> 

             <a href="<?php echo site_url('Image/view_images') ?>" class="btn btn-success" style="margin-left: 20px;">View Images</a>  
        </div>
      <div class="col-lg-3"></div>
    </div> 
  </div>
  <!-- jQuery CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <!-- Bootstrap JS links -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
</body>
</html>

Now you will have the view like this.

Now we can create the controller

Image.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('Image_model');
 }
 public function index()
 {
  $this->load->view('image_upload');
 }
 // add image from form
 public function add_image()
 {
  // CI form validation
  $this->form_validation->set_rules('image_name', 'Image Name', 'required');
  if ($this->form_validation->run() == FALSE){
   $this->load->view('image_upload');
        }
  else {
   // configurations from upload library
   $config['upload_path'] = './assets/images';
   $config['allowed_types'] = 'gif|jpg|png|jpeg';
   $config['max_size'] = '2048000'; // max size in KB
   $config['max_width'] = '20000'; //max resolution width
   $config['max_height'] = '20000';  //max resolution height
   // load CI libarary called upload
   $this->load->library('upload', $config);
   // body of if clause will be executed when image uploading is failed
   if(!$this->upload->do_upload()){
    $errors = array('error' => $this->upload->display_errors());
    // This image is uploaded by deafult if the selected image in not uploaded
    $image = 'no_image.png';    
   }
   // body of else clause will be executed when image uploading is succeeded
   else{
    $data = array('upload_data' => $this->upload->data());
    $image = $_FILES['userfile']['name'];  //name must be userfile
    
   }
   $this->Image_model->insert_image($image);
   $this->session->set_flashdata('success','Image stored');
   redirect('Image');
  }
 }
 // view images fetched from database
 public function view_images()
 {
  $data['images'] = $this->Image_model->get_images();
  $this->load->view('image_view', $data);
 }
}


Images that are taken through the form are inserted to the database with add_image function. But we need to sent these data via a model to insert into the image_data database table. So, we need to implement this functionality using a model.

Image_model.php


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Image_model extends CI_Model {
 public function insert_image($image)
 {
  // assign the data to an array
  $data = array(
   'image_id' => $this->input->post('image_id'),
   'image_name' => $this->input->post('image_name'),
   'image' => $image
  );
  //insert image to the database
  $this->db->insert('image_data', $data);
 }
 //get images from database
 public function get_images()
 {
  $this->db->select('*');
  $this->db->order_by('image_id');
  $query = $this->db->get('image_data');
  return $query->result();
 }
}

OK...You are now ready to upload images!!!

Give a name and select an image file(below 2MB).
Check the database after submission. Image details should be there. Image name will be the existed name of your image file.
Check the folder and find the uploaded image. My folder is assets/images.

Important:
If your configurations in the controller are violated by an image selected, it will not be uploaded to the folder or database. The image called no_image.png will be uploaded! Be careful to slelect the images which follows you configs.


Our final task is to create the view to display images in a table. We have already implemented the controller and model function needed to display the images. So, the only thing remaining is just create the image_view file and code.

image_view.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Image view</title>
  <!-- Bootstrap CSS link -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">
  <!-- Font Awesome CSS link -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/font-awesome/css/font-awesome.min.css">
</head>
<body>
  <div class="container">
    <h2 class="text-center" style="margin-top: 30px;">View Images</h2>
    <br>
    <div class="row">
      <div class="col-lg-2"></div>
      <div class="col-lg-8">
      <!-- check whether there are images or not -->
      <?php if (count($images)): ?>
      <div class="card" style="margin-bottom: 100px;">
        <div class="card-body">
          <h5 class="card-title"><i class="fa fa-user-circle-o"></i> Users stored in the database</h5>
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <th>Image ID</th>
                <th>Image Name</th>
                <th>Image</th>    
              </tr>      
            </thead>
            <tbody>
            <!-- start of foreach loop to display images -->
              <?php foreach($images as $row):?>
              <tr>
                <td><?php echo $row->image_id ?></td>
                <td><?php echo $row->image_name ?></td>
                <td><center><img class="thumbnail" style="height: 100px; width: 100px;" src="<?php echo base_url() ?>assets/images/<?php echo $row->image ?>"></center></td>
              </tr>
              <?php endforeach; ?> 
            <!-- end of foreach loop  -->
          </tbody>  
        </table>
      </div>
     </div>
    <?php else: ?>
    <!-- this text is shown when there are no images in the database -->
             <h4 style="color: red" class="text-center">No images in database</h4>
             <?php endif ?>
    </div>
    <div class="col-lg-2"></div>
    </div>
  </div>
  <!-- jQuery CDN -->
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> 
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <!-- Bootstrap JS links -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
</body>
</html>
Your view should have the format like this...


Completed!!!

Now it's time to check your application whether it is doing the job expected or not. Enjoy with uploading images!

As my final words, Codeigniter is an amazing PHP framework that does the things you needed simply. But I also found very difficult to learn the framework as a new comer. However I learned to handle it! I think it's not hard. Just need to understand the concepts.. So, try this one also and get used to build web applications with Codeigniter!

Good Luck guys!



20 Comments

  1. Thanx Dhananjay! It's a pleasure to me..

    ReplyDelete
  2. hello ;)
    Can i see your route and config file please ? i have a error with $form_validation
    Thank you
    Happy new year

    ReplyDelete
  3. Hello! Im building a member based site using CI and wanted to see how users can implement just by upload? I see having to have assets/image folder but will members of the site have to do that as well? Thank ya and this is a wonderful tutorial!!!

    ReplyDelete
    Replies
    1. members will not know about the backend processes as I know..If you are the person develop the system, you can configure all the things beforehand. No need of worrying about members!

      Delete
  4. Hello Sir,
    I was searching for image uploading class in codeigniter for 3 days and i was very upset for my unsuccessful attempts. But i got this blog and i uploaded all the files but there is a problem regarding this. I could not able to upload the image i dont know why . please help me .

    ReplyDelete
  5. Mine doesnt work. it keeps on uploading no image.

    ReplyDelete
    Replies
    1. may be this now old..have to recheck..i have not used codeigniter recently..sorry for the inconvenience!

      Delete
  6. doesn't work .'no_image.png' stored in database?not selected image always inseted 'no_image.png'
    .

    ReplyDelete
    Replies
    1. may be this now old..have to recheck..i have not used codeigniter recently..sorry for the inconvenience!

      Delete
  7. photo is uploaded in db but it doesn't view in table instead it shows a image tag

    ReplyDelete
    Replies
    1. may be this now old..have to recheck..i have not used codeigniter recently..sorry for the inconvenience!

      Delete
  8. Right here is the perfect webpage for anyone who really wants to find out about this topic. You know so much its almost tough to argue with you (not that I really will need to…HaHa). You certainly put a new spin on a topic that's been written about for decades. Wonderful stuff, just excellent!

    ReplyDelete
  9. Thanks buddy. This solves my problem. Hope next phase you will post "uploaded image edit / replace or delete". Thanks in advance.

    ReplyDelete
    Replies
    1. unfortunately I'm not practicing Codeigniter now. Sorry for that.

      Delete