How to upload file/image in CodeIgniter

CodeIgniter have an inbuilt upload library that allows to upload file.  You can specify various preference like – destination path, valid file types, max file size, etc.

In this tutorial, I create a simple example to demonstrate file uploading in CodeIgniter.

How to upload file in CodeIgniter


Contents

  1. Create directory
  2. Controller
  3. View
  4. Conclusion

 

1. Create directory

Navigate to project root directory and create uploads directory to store uploading files from the controller.

How to upload file in CodeIgniter


 

2. Controller

Navigate to application/controllers/ directory and create a User.php file.

On <form> submit define upload file preference  e.g. upload directory, allowed file types, max size, file name, etc. Pass this preference while loading upload library.

With $this->upload->do_upload upload file where pass name of file variable as parameter.

Completed Code

<?php<?phpdefined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
 
 public function index(){
 // load base_url  
 $this->load->helper('url');
 
 // Check form submit or not 
 if($this->input->post('upload') != NULL ){ 
   $data = array(); 
   if(!empty($_FILES['file']['name'])){ 
    // Set preference 
    $config['upload_path'] = 'uploads/'; 
    $config['allowed_types'] = 'jpg|jpeg|png|gif'; 
    $config['max_size'] = '100'; // max_size in kb 
    $config['file_name'] = $_FILES['file']['name']; 

    // Load upload library 
    $this->load->library('upload',$config); 
   
    // File upload
    if($this->upload->do_upload('file')){ 
     // Get data about the file
     $uploadData = $this->upload->data(); 
     $filename = $uploadData['file_name']; 
     $data['response'] = 'successfully uploaded '.$filename; 
    }else{ 
     $data['response'] = 'failed'; 
    } 
   }else{ 
    $data['response'] = 'failed'; 
   } 
   // load view 
   $this->load->view('user_view',$data); 
  }else{
   // load view 
   $this->load->view('user_view'); 
  } 
 }
}

 

3. View

Navigate to application/views/ directory and create a user_view.php file.

Create a file and button element in the <form>.

Completed Code

<!doctype html>
<html>
 <head>
  <title>How to upload file in CodeIgniter</title>
 </head>
 <body>
  <b><?php if(isset($response)) echo $response; ?></b>
  <form method='post' action='<?php echo base_url(); ?>' enctype='multipart/form-data'>

   <input type='file' name='file' > <br/><br/>
   <input type='submit' value='Upload' name='upload' />
  </form>
 </body>
</html>

 

4. Conclusion

For upload a file you need to load upload library and depending on the requirement define your preference.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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