How to upload image in Codeigniter step by step

hi, friends today I will show you the best and easiest steps to upload image in Codeigniter. I will show you how to upload the image by using a single optimize function in Codeigniter.

Steps to follow

  • Create the assets folder/dir in the application folder/dir.
  • Create uploads folder/dir in the assets folder/dir.
  • Add enctype=”multipart/form-data” in your form tag.
"<form action="<?php echo base_url('user/create_profile');?>" method="post" enctype="multipart/form-data">
  • Add “input type file” tag in the form
"<input type="file" class="form-control" id="pwd"  name="image">
  • copy the below function do upload in your control.
public function do_upload($input_name)
        //todo:set unique name to file
        $date = new DateTime();
        $startdata = $date->format('YmdHis');
        $newName = str_replace('/', '', $startdata) . 1;
        $config['file_name'] = $newName;
        $config['upload_path'] = 'application/assets/uploads/';
        $config['allowed_types']        = 'gif|jpg|png';
//      $config['max_size']             = 2048;
//      $config['max_width']            = 1920;
//      $config['max_height']           = 1080;

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

        if ( ! $this->upload->do_upload($input_name))
            $error = array('error' => $this->upload->display_errors());
            return false;
            $data = array('upload_data' => $this->upload->data());
            $image = $data['upload_data']['file_name'];
            return $image;
  • Call your function in the post request where you are submitting your form

$image['image'] = $this->do_upload('image');

now in this the name “image” in $this->do_upload(‘image’); is the name of file form input tag as we set in form.

$image[‘image’] is the unique name of an image generated by the function you can view image in assets/uploads dir we create in 1st step and you insert the image name in the database.

Good luck guys, I will write the next tutorial on how to upload images and store name into database.

Scroll to Top