Codeigniter File Download Example

3

In this tutorial I will show you how to download file using codeigniter. This code is pretty much simple to understand, Here we are using force_download() function, which will help to download the file content from server location.

Tools and Technologies

To execute this example, I am using latest version of codeigniter framework 3.1.0

  1. Php Codeigniter 3.1.0
  2. XAMPP / Php 5.6

As you know that Php Codeigniter framework is popular for minimum configuration (almost Zero configuration). To execute this example, you have do below configurations in config.php file. Refer base url and route configurations.

Codeigniter base url configuration

Codeigniter routes configuration

Here I have defined below routes to connect to respected download controller. You can configure routes as per your requirement.

FileController.php

Lets create the FileController class under folder name application/controllers along with index() and download(fileName = NULL) functions.

Load codeigniter download helper $this->load->helper('download') class in controller construct function.

download() – function has one parameter called as fileName, Which we are going to read or download the from server location. First we will check if specified is exist or not using file_exists() function, If it is available then download it, otherwise redirect to base url.

file_get_contents() – function is used to read the file contents.

force_download() – function is used to download the file, Which also generates respected headers that force to download the file.

If you want to directly download the file using server path or URL , then use force_download('/path/to/abc.zip', NULL);

welcome.php

Create welcome.php file under folder application/views. Just simply add the download button along with file URL.

Run

Enter the url http://localhost/codeigniterexamples in your browser, It will show you the default page content. Once you click on (Download imp.zip) button, It will start downloading the imp.zip file.

Leave A Reply

Your email address will not be published.