Last updated on January 17, 2018
CodeIgniter is a PHP framework, CodeIgniter has a number of helpers and libraries, which will reduce the development time and we can write more reliable and bugs free Code. This post is about uploading files in CodeIgniter, CodeIgniter has upload library, by using this Class we can upload files to the server very easily.
For Uploading files, as usually we need a Simple HTML form, with an input field and submit button.
you may like : Multiple File Upload using dropzone.js and Codeigniter
In CodeIgniter, views Create a new file called imageupload_view.php.
Upload Form
Create A New Controller: controllers/Imageupload.php
class Imageupload extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); } function index() { $this->load->view('imageupload_view', array('error' => ' ' )); } function doupload() { $name_array = array(); $count = count($_FILES['userfile']['size']); foreach($_FILES as $key=>$value) for($s=0; $s<=$count-1; $s++) { $_FILES['userfile']['name']=$value['name'][$s]; $_FILES['userfile']['type'] = $value['type'][$s]; $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; $_FILES['userfile']['error'] = $value['error'][$s]; $_FILES['userfile']['size'] = $value['size'][$s]; $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $this->load->library('upload', $config); $this->upload->do_upload(); $data = $this->upload->data(); $name_array[] = $data['file_name']; } $names= implode(',', $name_array); /* $this->load->database(); $db_data = array('id'=> NULL, 'name'=> $names); $this->db->insert('testtable',$db_data); */ print_r($names); } }
NOTE: We have configured upload library to store uploads in “uploads” directory with “upload_path” config key, so create a uploads directory in the project root directory.
And that is it. Now you should be able to access upload page with – http:://yourDomin/imageupload
or http:://yourDomin/index.php/imageupload
(base on your configurations and directory structure URL will change). Customize it to your needs, the basics are there already. And good luck!
I hope this tutorial helps you please don’t forget to give us your feedback in comments.