How to Upload Image and File in CodeIgniter

This tutorial discusses the process of creating a CodeIgniter based file upload component that could be easily used to upload images and other files with ease. You could validate and even restrict file size and type during the upload process.



Uploading Images in CodeIgniter

File uploading in CodeIgniter has two main parts. The frontend and the backend. The frontend is handled by the HTML form that uses the form input type file. On the backend, the file upload library processes the submitted input from the form and writes it to the upload directory.

 Creating Database Table (Members):

Before start to writing the source code, make a sql table into your web application’s database. For this example you can make a members table into the database with some basic fields. The members table SQL would like the below.

`id` int(11) NOT NULL AUTO_INCREMENT,

 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

 `image` text COLLATE utf8_unicode_ci NOT NULL,


Image.php - Controller

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Image extends CI_Controller {

public function __construct()

{

parent::__construct();

$this->load->database();

$this->load->model('Image_model');

}

public function index()

{

// ---------------------------list-------------------------------------------

$data_image['results'] = $this->Image_model->readImage();

// ---------------------------Upload-------------------------------------------

$this->load->view('image_view',$data_image);

$config = [

'upload_path'       => 'uploads/',

'allowed_types'     => 'gif|png|jpg|jpeg|PNG|JPG|JPEG|',

'overwrite'         => false,

'maintain_ratio'    => true,

'encrypt_name'      => true,

'remove_spaces'     => true,

'file_ext_tolower'  => true

];

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

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

$data = $this->upload->data();

$image = $config['upload_path'].$data['file_name'];

}

else{

if(!empty($_FILES['image']['name'])){

$error = array('error' => $this->upload->display_errors());

$this->session->set_flashdata('exception',$this->upload->display_errors());

}

}

$data['image']=(!empty($image)?$image:$this->input->post('image'));

if($this->input->post('Sumbit'))

{

// ---------------------------Upload End-------------------------------------------

// ---------------------------input Values-------------------------------------------

$data = array(

'name' => $this->input->post('name'),

'image' => $image

);

// ---------------------------input Values End-------------------------------------------

// ---------------------------Model-------------------------------------------

$response=$this->Image_model->index_insert($data);

// ---------------------------Model end-------------------------------------------

// ---------------------------Successfully Msg-------------------------------------------

if($response==true){

echo "Records Saved Successfully";

}

else{

echo "Insert error !";

}

// ---------------------------End-------------------------------------------

redirect("image/index");

}

}

public function deletedata($id = null)

{

if ($this->Image_model->deleterecords($id)) {

echo "Data deleted successfully !";

} else {

echo "Error !";

}

// redirect("image/index");

}

}

?>(code-box)

Image_model.php

<?php
class Image_model extends CI_Model
  {
public function index_insert($data)
{
$this->db->insert('uploadimage',$data);
// echo $this->db->last_query();die();
return true;
}
public function readImage()
{
return $this->db->select("*")
->from('uploadimage')
->order_by('id', 'desc')
->get()

->result();
}
function deleterecords($id)
{
$this->db->where("id", $id);
$this->db->delete("uploadimage");
return true;
}
}
?> (code-box)


 image_view.php -view page

<!DOCTYPE html>

<html>

  <style>

  input[type=text], select {

  width: 100%;

  padding: 12px 20px;

  margin: 8px 0;

  display: inline-block;

  border: 1px solid #ccc;

  border-radius: 4px;

  box-sizing: border-box;

  }

  input[type=submit] {

  width: 100%;

  background-color: #4CAF50;

  color: white;

  padding: 14px 20px;

  margin: 8px 0;

  border: none;

  border-radius: 4px;

  cursor: pointer;

  }

  input[type=submit]:hover {

  background-color: #45a049;

  }

  div {

  border-radius: 5px;

  background-color: #f2f2f2;

  padding: 20px;

  }

  .container{

  width: 800px;

  margin: auto;

  }

  </style>

  <body>

    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

    <div class="container">

      <button onclick="location.reload();">Refresh Page</button>

      <!-- -----------------------form----------------------------------------- -->

      <h2>Upload Image form</h2>

      <form method="post" enctype='multipart/form-data' action="<?php echo base_url('image/index')?>">  <!-- image/index   URL-->

      <label for="name">Name</label>

      <input type="text" id="email" name="name" value="">

      <br>

      <br>

      <label for="image">Image</label>

      <input type="file" id="image" name="image">

      <br>

      <br>

      <input type="submit" value="Submit" name="Sumbit">

      <!-- <input type="submit" name="edit" value="Edit" /> -->

    </form>

    <!-- -----------------------form end----------------------------------------- -->

    <h2>Upload Image</h2>

    <table class="w3-table-all w3-card-4">

      <tr>

        <th>Sl No</th>

        <th>Name</th>

        <th>Image</th>

        <th>Delete</th>

      </tr>

      <?php $sl = 1; ?>

      <?php foreach($results as $image) : ?>

      <tr>

        <td><?php echo $sl++; ?></td>

        <td> <?php echo $image->name; ?></td>

        <td><img src="<?php echo base_url().$image->image ?>" width="150"></td>

        <td>   <a href="<?php echo base_url("image/deletedata/$image->id") ?>">Delete</a> |

      </td>

    </tr>

    <?php endforeach; ?>

  </table>

</div>

</body>

</html> (code-box)

Our website uses cookies to enhance your experience. Learn More
Accept !