CodeIgniter File Uploading

CodeIgniter's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.

Uploading a file involves the following general process:

  • An upload form is displayed, allowing a user to select a file and upload it.
  • When the form is submitted, the file is uploaded to the destination you specify.
  • Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set.
  • Once uploaded, the user will be shown a success message.

Creating the Upload Form

Using a text editor, create a form called upload_form.php. In it, place this code and save it to your application/views/ directory:

<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>
<div class="container">
  <div class="col-md-2"></div>
     <div class="col-md-8" style="margin-top:20px">
           echo form_open_multipart('upload/do_upload');
           if (isset($error))
           echo '<p>'.$error.'</p>';
        <div class="form-group">
            <label for="email">File Upload:</label>
            <input type="file" id="file" name="upload_file" />
        <button type="submit" class="btn btn-success">Upload</button>
              echo form_close(); 
        <p>Your file was successfully uploaded!<p>
        <?php echo "<pre>".json_encode($upload_data, JSON_PRETTY_PRINT)."</pre>";
     <div class="col-md-2"></div>

The Controller

Using a text editor, create a controller called Upload.php. In it, place this code and save it to your application/controllers/ directory:

   class Upload extends CI_Controller {
      public function __construct() { 
         $this->load->helper(array('form', 'url')); 
      public function index() { 
      public function do_upload() { 
         $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);
         if ( ! $this->upload->do_upload('upload_file')) {
            $error = $this->upload->display_errors(); 
            $this->load->view('upload_form', compact('error')); 
         else { 
            $upload_data = $this->upload->data(); 
            $this->load->view('upload_form', compact('upload_data')); 

To try your form, visit your site using a URL similar to this one:


It will produce the following screen:

Codeigniter Upload Form
Codeigniter Upload Form