How to Download File from Database in CodeIgniter Example

171

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.

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.

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.

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.

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.

 

Leave A Reply

Your email address will not be published.