Skip to main content

CodeIgniter File Upload with Flashdata

Screenshot
Body

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this tutorial. After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP. Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_fileupload so I'm using the below code.
  1. localhost/codeigniter_fileupload
codeigniter successful install

Creating our Database

First we are going to create our database for this tutorial. 1. Open your phpMyAdmin. 2. Create a new database named codeigniter. 3. Click the database that we created, click SQL tab then paste the below code or import the included .sql file in the downloadable of this source code located in db folder.
  1. CREATE TABLE `files` (
  2. `filename` varchar(150) NOT NULL,
  3. `description` text NOT NULL,
database mysql

Connecting our App to MySQL

Next, we're going to connect our codeigniter application to the database that we created earlier. 1. In your codeigniter app folder, open database.php located in application/config folder. 2. Update database.php with your credential the same as what I did in the image below. database is where we define the database that we created earlier. database config codeigniter

Configuring our Base URL

Next, we configure our base url to tell codeigniter that this is the URL of our site/application. We're gonna be using this a lot that's why we need to configure this. 1. In your codeigniter app folder, open config.php located in application/config folder. 2. Find and edit the ff line:
  1. $config['base_url'] = 'http://localhost/codeigniter_fileupload/';
where codeigniter_fileupload is the name of your app folder.

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion. Create a file named Files_model.php in application/models folder of our app and put the ff codes.
  1. <?php
  2. class Files_model extends CI_Model {
  3. function __construct(){
  4. parent::__construct();
  5. $this->load->database();
  6. }
  7.  
  8. public function getAllFiles(){
  9. $query = $this->db->get('files');
  10. return $query->result();
  11. }
  12.  
  13. public function insertfile($file){
  14. return $this->db->insert('files', $file);
  15. }
  16.  
  17. }
  18. ?>

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models. Create a file named Upload.php in application/controllers folder of our app and put the ff codes.
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class Upload extends CI_Controller {
  5.  
  6. function __construct() {
  7. parent::__construct();
  8. //load our helper
  9. $this->load->helper('url');
  10. //load our model
  11. $this->load->model('files_model');
  12. }
  13.  
  14. public function index(){
  15. //load session library to use flashdata
  16. $this->load->library('session');
  17. //fetch all files i the database
  18. $data['files'] = $this->files_model->getAllFiles();
  19. $this->load->view('file_upload', $data);
  20. }
  21.  
  22. public function insert(){
  23. //load session library to use flashdata
  24. $this->load->library('session');
  25.  
  26. //Check if file is not empty
  27. if(!empty($_FILES['upload']['name'])){
  28. $config['upload_path'] = 'upload/';
  29. //restrict uploads to this mime types
  30. $config['allowed_types'] = 'jpg|jpeg|png|gif';
  31. $config['file_name'] = $_FILES['upload']['name'];
  32.  
  33. //Load upload library and initialize configuration
  34. $this->load->library('upload', $config);
  35. $this->upload->initialize($config);
  36.  
  37. if($this->upload->do_upload('upload')){
  38. $uploadData = $this->upload->data();
  39. $filename = $uploadData['file_name'];
  40.  
  41. //set file data to insert to database
  42. $file['description'] = $this->input->post('description');
  43. $file['filename'] = $filename;
  44.  
  45. $query = $this->files_model->insertfile($file);
  46. if($query){
  47. header('location:'.base_url().$this->index());
  48. $this->session->set_flashdata('success','File uploaded successfully');
  49. }
  50. else{
  51. header('location:'.base_url().$this->index());
  52. $this->session->set_flashdata('error','File uploaded but not inserted to database');
  53. }
  54.  
  55. }else{
  56. header('location:'.base_url().$this->index());
  57. $this->session->set_flashdata('error','Cannot upload file.');
  58. }
  59. }else{
  60. header('location:'.base_url().$this->index());
  61. $this->session->set_flashdata('error','Cannot upload empty file.');
  62. }
  63.  
  64. }
  65.  
  66. }

Creating our Default Route

Next, we are going to set our default route so that whenever we haven't set up a controller to use, this default controller will be used instead. Open routes.php located in application/config folder and set the default route to our user controller. Note: While we name controllers using CAPITAL letter in this first letter, we refer to them in SMALL letter.
  1. $route['default_controller'] = 'upload';

Creating our View

Lastly, we create the views of our app. Take note that I've use Bootstrap in the views. You may download bootstrap using this link. Create the ff file inside application/views folder. file_upload.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter File Upload</title>
  6. <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h1 class="page-header text-center">CodeIgniter File Upload with Flashdata</h1>
  11. <div class="row">
  12. <div class="col-sm-4">
  13. <h3>File Upload Form</h3>
  14. <form method="POST" action="<?php echo base_url(); ?>index.php/upload/insert" enctype="multipart/form-data">
  15. <div class="form-group">
  16. <label>Description:</label>
  17. <input type="text" name="description" class="form-control" required>
  18. </div>
  19. <div class="form-group">
  20. <label>File:</label>
  21. <input type="file" name="upload" required>
  22. </div>
  23. <button type="submit" class="btn btn-primary">Save</button>
  24. </form>
  25. <?php
  26. if($this->session->flashdata('success')){
  27. ?>
  28. <div class="alert alert-success text-center" style="margin-top:20px;">
  29. <?php echo $this->session->flashdata('success'); ?>
  30. </div>
  31. <?php
  32. }
  33.  
  34. if($this->session->flashdata('error')){
  35. ?>
  36. <div class="alert alert-danger text-center" style="margin-top:20px;">
  37. <?php echo $this->session->flashdata('error'); ?>
  38. </div>
  39. <?php
  40. }
  41. ?>
  42. </div>
  43. <div class="col-sm-8">
  44. <table class="table table-bordered table-striped">
  45. <thead>
  46. <tr>
  47. <th>ID</th>
  48. <th>Filename</th>
  49. <th>Description</th>
  50. </tr>
  51. </thead>
  52. <tbody>
  53. <?php
  54. foreach($files as $file){
  55. ?>
  56. <tr>
  57. <td><?php echo $file->id; ?></td>
  58. <td><?php echo $file->filename; ?></td>
  59. <td><?php echo $file->description; ?></td>
  60. </tr>
  61. <?php
  62. }
  63. ?>
  64. </tbody>
  65. </table>
  66. </div>
  67. </div>
  68. </div>
  69. </body>
  70. </html>
That ends the explanation for this tutorial. Happy Coding :)

Add new comment