How to Download Files in CodeIgniter

This tutorial tackles how to download/force download files from your database in CodeIgniter. In this tutorial, we're gonna be using the "force_download()" class of the CodeIgniter to force download files. CodeIgniter is a lightweight PHP framework that uses MVC(Model-View-Controller) architecture.

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.11 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 the "htdocs" folder of my XAMPP's directory.

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_download" so I'm using the below code.

  1. http://localhost/codeignter_download
codeigniter successful install

Creating our Upload Functionality

To practice this download functionality, we're gonna be using my tutorial, CodeIgniter File Upload, which uploads file into our database that we can download.

Removing index.php in our URLs

Next, to improve our app, we're going to remove index.php in our URL's by creating a .htaccess file. Please refer to my tutorial, How to Remove Index.Php in the URL of Codeigniter Application, for the steps on how to do this.

Creating our Database

Next, we're going to create the database of our app.

I've included .sql file located in db folder of the downloadable of this tutorial. Just create a new database in your phpMyAdmin named codeigniter and import this database. If you have no idea on how to import, please refer to my tutorial How import .sql file to restore MySQL database.

Or, you can also add our sample table in our database programmatically. Use the ff codes.

  1. CREATE TABLE `files` (
  2. `filename` varchar(150) NOT NULL,
  3. `description` text NOT NULL

Connecting our App into our Database

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 below.
  1. $db['default'] = array(
  2. 'dsn' => '',
  3. 'hostname' => 'localhost',
  4. 'username' => 'root',
  5. 'password' => '',
  6. 'database' => 'codeigniter',
  7. 'dbdriver' => 'mysqli',
  8. 'dbprefix' => '',
  9. 'pconnect' => TRUE,
  10. 'db_debug' => (ENVIRONMENT !== 'production'),
  11. 'cache_on' => FALSE,
  12. 'cachedir' => '',
  13. 'char_set' => 'utf8',
  14. 'dbcollat' => 'utf8_general_ci',
  15. 'swap_pre' => '',
  16. 'encrypt' => FALSE,
  17. 'compress' => FALSE,
  18. 'stricton' => FALSE,
  19. 'failover' => array(),
  20. 'save_queries' => TRUE
  21. );

Configuring our Base URL

Next, we configure our base url to tell codeigniter that this is the URL of our site/application.

  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_download/';

The "codeigniter_download" is the name of our app.

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. public function download($id){
  18. $query = $this->db->get_where('files',array('id'=>$id));
  19. return $query->row_array();
  20. }
  21.  
  22. }
  23. ?>

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models.

Create a file named "Files.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 Files 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','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. public function download($id){
  67. $this->load->helper('download');
  68. $fileinfo = $this->files_model->download($id);
  69. $file = 'upload/'.$fileinfo['filename'];
  70. force_download($file, NULL);
  71. }
  72.  
  73. }

Configuring our Default Controller

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'] = 'files';

Creating our View (Interface)

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.

strongCreate the ff files inside application/views folder.

file_upload.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Download</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 Download</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(); ?>files/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. <th>Download</th>
  51. </tr>
  52. </thead>
  53. <tbody>
  54. <?php
  55. foreach($files as $file){
  56. ?>
  57. <tr>
  58. <td><?php echo $file->id; ?></td>
  59. <td><?php echo $file->filename; ?></td>
  60. <td><?php echo $file->description; ?></td>
  61. <td><a href="<?php echo base_url().'files/download/'.$file->id; ?>" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-download-alt"></a></td>
  62. </tr>
  63. <?php
  64. }
  65. ?>
  66. </tbody>
  67. </table>
  68. </div>
  69. </div>
  70. </div>
  71. </body>
  72. </html>

That's it, test your you have created it works. And if ever you have missed something you can download the working source code I have created and try to compare look what have you missed.

That ends this tutorial. I hope this tutorial will help you with what your are lookign for and for your future CI Projects.

Happy Coding :)

Add new comment