Downloading Files Using Codeigniter

Codeigniter

Hello friends,

In this tutorial i am going to explain how to download files using codeigniter application. For this use PHP codeigniter framework.

Initially create a controller called FileDownload.php under application/controllers directory in your codeigniter application. And write following code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
class FileDownload extemds CI_Controller
{
 function __construct(){
  parent::__construct();
  $this->load->helper(['url',download]);
 }
 public function index()
 {
     $this->load->view('fileDownload_v');
 }
 public function download()
 {
     $fileContent = file_get_contents(base_url().'assets/download.pdf'); 
     $fileName = 'download.pdf'; 
     force_download($fileName, $fileContent,true);
     redirect('fileDownload/index');
}
?>

Using codeigniter download helper, we can easily download the file to our desktop. So write the code to load download helper in your controller or auto load this helper in autoload.php file.

file_get_contents()function reads all contents from the download.pdf file.

force_download() function downloads the files to your system.

paremeters–>

  •  $filename – Here we specify the name you want to downloaded the file
  • $filecontent – specify the contents of the file. file_get_contents() function reads all contents in the file
  • $mime  – Specify the mime type. it is a Boolean value.  If it is set to true actual mime type is sent.

Create a new folder called assets in your root directory and contains the file called download.pdf, then only you can download the file.

After that create a view page called ‘fileDownload_v.php’ page in your application/views directory. Then write following code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
   <head>
      <title>File Download Using Codeigniter</title>
      <!-- Latest compiled and minified CSS --> 
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.
com/bootstrap/3.3.7/css/bootstrap.min.css">
      <!-- jQuery library --> 
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/
3.2.1/jquery.min.js"></script>
     <!-- Latest compiled JavaScript --> 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/
3.3.7/js/bootstrap.min.js"></script> 
   </head>
   <body>
   <div class="container">
      <div class="row">
         <a href = "<?= site_url('fileDownload/download') ?>" class=
"btn" title="File Download" />File Download</a>
      </div>
   </div>
   </body>
</html>

Run the code and Click the download button to download the file.

Leave a Reply

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