File upload example in Codeigniter 2.1.4

File upload example in Codeigniter 2.1.4. There is file upload class, in codeigniter, which permits you to upload the file or files. This class also permits you to set various preferences such as destination where the file will be uploaded, restrition on file types, restriction on file size, whether a file name should be encrypted or not, maximum length of the file name etc.

Below are the simple few processes for uploading a file

A form with input type file is required so that user can select the file using the browse button
When the form is submitted, the file is validated to make sure that the file is uploaded against the preferences you set
Once the file is uploaded successfully to the specified destination, the success message is shown
The output in the browser

When the upload form is shown to the user
file upload example in codeigniter

When user submits without selecting file
file upload example in codeigniter

When user selects a file and submit the form
file upload example in codeigniter

Directory structure

file upload example in codeigniter

Create the table in the database

Here table name is files

CREATE TABLE `files` (
  `file_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `file_orig_name` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `file_path` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `upload_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`file_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;


Go to application/config/database.php and change the value as per your database settings

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'cdcol';
$db['default']['dbdriver'] = 'mysql';


Go to application/config/autoload.php and change the value as shown below

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url', 'file', 'text', 'form');


Create the view – upload form

As shown previously in the directory structure image, you have to create a form called file_upload.php under application/views/ folder

<title>Welcome to CodeIgniter</title>
<style scoped="scoped" type="text/css">
body {
                background-color: #fff;
                margin: 40px;
                font: 13px/20px normal Helvetica, Arial, sans-serif;
                color: #4F5155;
                margin: 0 15px 0 15px;
                margin: 10px;
                border: 1px solid #D0D0D0;
                -webkit-box-shadow: 0 0 8px #D0D0D0;
            .error {
                color: #E13300;
            .info {
                color: gold;
            .success {
                color: darkgreen;
<div id="container">
<h1>File Upload Example</h1>
<div id="body">
<p>Select a file to upload</p>
                if (isset($success) && strlen($success)) {
                    echo '<div class="success">';
                    echo '<p>' . $success . '</p>';
                    echo '</div>';
                if (isset($errors) && strlen($errors)) {
                    echo '<div class="error">';
                    echo '<p>' . $errors . '</p>';
                    echo '</div>';
                if (validation_errors()) {
                    echo validation_errors('<div class="error">', '</div>');
                    $attributes = array('name' => 'file_upload_form', 'id' => 'file_upload_form');
                    echo form_open_multipart($this->uri->uri_string(), $attributes);
<p><input name="file_name" id="file_name" readonly="readonly" type="file" /></p>
<p><input name="file_upload" value="Upload" type="submit" /></p>
                    echo form_close();


In the above form I have used codigniter’s form helper tags. Also notice when we need to upload a file or files we have to use the enctype=”multipart/form-data” and hence we have used form_open_multipart(). If there is no need to upload a file then we can use only form_open(). We have passed some attributes, in form_open_multipart(), which will be added in the html’s form tag. We have also some other variables like $errors, $success which will show errors and success messages respectively. We have codeigniter’s built-in validation_errors() function which will show also error messages.

File upload Controller

We have already default controller called welcome.php under application/controllers/. If you want you can also create your own controller. You can find the explainations in the comment for important statements.

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Welcome extends CI_Controller {
    //variable for storing error message
    private $error;
    //variable for storing success message
    private $success;
    function __construct() {
        //load this to validate the inputs in upload form
        //load this to transact with database
        $this->load->model('file_model', 'file');
    //appends all error messages
    private function handle_error($err) {
        $this->error .= $err . "\r\n";
    //appends all success messages
    private function handle_success($succ) {
        $this->success .= $succ . "\r\n";
    //file upload action
    public function index() {
        //check whether submit button was clicked or not
        if ($this->input->post('file_upload')) {
            //set preferences
            //file upload destination
            $config['upload_path'] = './upload/';
            //allowed file types. * means all types
            $config['allowed_types'] = '*';
            //allowed max file size. 0 means unlimited file size
            $config['max_size'] = '0';
            /max file name size
            $config['max_filename'] = '255';
            //whether file name should be encrypted or not
            $config['encrypt_name'] = TRUE;
            //store file info once uploaded
            $file = array();
            //check for errors
            $is_file_error = FALSE;
            //check if file was selected for upload
            if (!$_FILES) {
                $is_file_error = TRUE;
                $this->handle_error('Select at least one file.');
            //if file was selected then proceed to upload
            if (!$is_file_error) {
                //load the preferences
                $this->load->library('upload', $config);
                //check file successfully uploaded. 'file_name' is the name of the input
                if (!$this->upload->do_upload('file_name')) {
                    //if file upload failed then catch the errors
                    $is_file_error = TRUE;
                } else {
                    //store the file info
                    $file = $this->upload->data();
            // There were errors, we have to delete the uploaded files
            if ($is_file_error) {
                if ($file) {
                    $file = './upload/' . $file['file_name'];
                    if (file_exists($file)) {
            if (!$is_file_error) {
                //save the file info in the database
                $resp = $this->file->save_file_info($file);
                if ($resp === TRUE) {
                    $this->handle_success('File was successfully uploaded.');
                } else {
                    //if file info save in database was not successful then delete from the destination folder
                    $file = './upload/' . $file['file_name'];
                    if (file_exists($file)) {
                    $this->handle_error('Error while saving file info to Database.');
        //load the error and success messages
        $data['errors'] = $this->error;
        $data['success'] = $this->success;
        //load the view along with data
        $this->load->view('file_upload', $data);
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */


The Model

This model class is responsible for interacting with the database and save the file info to the database.

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 * Description of file_model
 * @author Admin
class file_model extends CI_Model {
    //table name
    private $file = 'files';   // files
    function __construct() {
    function save_file_info($file) {
        //start db traction
        //file data
        $file_data = array(
            'file_name' => $file['file_name'],
            'file_orig_name' => $file['orig_name'],
            'file_path' => $file['full_path'],
            'upload_date' => date('Y-m-d H:i:s')
        //insert file data
        $this->db->insert($this->file, $file_data);
        //complete the transaction
        //check transaction status
        if ($this->db->trans_status() === FALSE) {
            $file_path = $file['full_path'];
            //delete the file from destination
            if (file_exists($file_path)) {
            //rollback transaction
            return FALSE;
        } else {
            //commit the transaction
            return TRUE;
/* End of file file_model.php */
/* Location: ./models/file_model.php */


For more information on file upload you can have a look at this

That’s all. Thanks for your reading. Please do not forget to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *