Download File from Database in CodeIgniter


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.

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.

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.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Files management class created by CodexWorld
 */
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($fileNULL);
        }
    }
}

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.

<?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.

<?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="dwn">Download</a>
    </div>
</div>
<?php } } ?>

Files are listed from the database like the below.

codeigniter-download-file-preview-codexworld

Recommended Tutorials For You

Leave a reply

CONNECT WITH CODEXWORLD