Download File from Database in CodeIgniter Framework

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on PinterestPrint this pageEmail this to someone

CodeIgniter provides some built-in helpers to make easy to implement some useful functionality in the web application. Download Helper is one of them that lets you integrate file download feature quickly in CodeIgniter. In this CodeIgniter tutorial, we will show you how easily you can download file or image from database using Download Helper.

The Download Helper have a force_download() function that generates server headers which force data to be downloaded to your computer. You can download existing file from the server using force_download() function. The force_download() function accepts 3 parameters – $filename (string), $data (mixed), and $set_mime (bool). To download the existing file you’ll need to use the force_download() function like the following.

1
force_download('/path/to/photo.jpg', NULL);

Here we’ll provide an example script to download files or images from database in CodeIgniter application. The following functionalities will be implemented in this script.

All the files would be listed from the database which already exists in the upload folder (uploads/files/).
Files will be listed with preview and a download link.
By clicking on the “Download” link the respective file downloads from the directory.
File Upload Directory

Create a directory where you want to store the uploaded files. The uploaded files are stored in the uploads/files directory of the application root.

Database Table Creation

To store the files information a table is needed into MySQL database. The following SQL creates a files table with some basic required fields.

1
2
3
4
5
6
7
8
9
10
CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Controller (Files.php)

Files controller handles the files listing and download functionality. It contains three functions __construct(), index(), and download().
__construct() – The File model is loaded for fetching files data from the database.
index() – The file’s data is fetched from the database using File model and passed to the view.
download() – The requested file is downloaded based on the provided ID from the directory.
In download() function, the file information is fetched from the database and force_download() is used to download the respective file from the directory.

READ  How to Remove index.php from URL in CodeIgniter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Files management class created by QueryAnswer
 */
class Files extends CI_Controller {
   
    function __construct() {
        parent::__construct();
        $this->load->model('file');
    }
   
    public function index(){
        $data = array();
       
        //get files from database
        $data['files'] = $this->file->getRows();
       
        //load the view
        $this->load->view('files/index', $data);
    }
   
    public function download($id){
        if(!empty($id)){
            //load download helper
            $this->load->helper('download');
           
            //get file info from database
            $fileInfo = $this->file->getRows(array('id' => $id));
           
            //file path
            $file = 'uploads/files/'.$fileInfo['file_name'];
           
            //download file from directory
            force_download($file, NULL);
        }
    }
}
?>

Model (File.php)

The File model handles all the database related works and it contains one function getRows(). The getRows() function get records from the files table and returns the requested data.

READ  Login with Facebook in CodeIgniter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{
    /*
     * get rows from the files table
     */
    function getRows($params = array()){
        $this->db->select('*');
        $this->db->from('files');
        $this->db->where('status','1');
        $this->db->order_by('created','desc');
        if(array_key_exists('id',$params) && !empty($params['id'])){
            $this->db->where('id',$params['id']);
            //get records
            $query = $this->db->get();
            $result = ($query->num_rows() > 0)?$query->row_array():FALSE;
        }else{
            //set start and limit
            if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
                $this->db->limit($params['limit'],$params['start']);
            }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
                $this->db->limit($params['limit']);
            }
            //get records
            $query = $this->db->get();
            $result = ($query->num_rows() > 0)?$query->result_array():FALSE;
        }
        //return fetched data
        return $result;
    }

}
?>

View (files/index.php)

This view is loaded by the index() method of the Files controller. All the files are listed with title, preview, and download link. When the user clicks on the Download link, respective file is downloaded by the download() method of Files controller.

READ  CodeIgniter Architecture
1
2
3
4
5
6
7
8
9
10
11
<?php if(!empty($files)){ foreach($files as $frow){ ?>
<div class="file-box">
    <div class="box-content">
        <h5><?php echo $frow['title']; ?></h5>
        <div class="preview">
            <embed src="<?php echo base_url().'uploads/files/'.$frow['file_name']; ?>">
        </div>
        <a href="<?php echo base_url().'files/download/'.$frow['id']; ?>" class="Download">Download</a>
    </div>
</div>
<?php } } ?>

Files are listed from the database like the below.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on PinterestPrint this pageEmail this to someone

Leave a Reply

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