Download Helper Codeigniter
Download Helper Codeigniter: The download helper function is used to download data from the server to your computer. The data can be any format like text, jpg, mp3, mp4, etc.
Loading the Download Helper
Before using the download function, you must load the helper in the controller's files.
Syntax
$this->load->helper(‘download’);
Function of Download Helpers
- force_download(): The function downloads the data forcefully in the system.
Syntax
force_download( [ $filename =’ ‘ [, $data = ‘ ‘ [, $set_mime = FALSE ] ] ]);
Parameters
- $filename: It defines the downloaded file.
- $data: It denotes the file content.
- $set_mime (bool): It sets the MIME value to true or false.
Download a run time file from the server
You can create a file that can download at run time from the server. To download a file from the server, create a Tests.php file in application/controller folder and write the following program.
Tests.php
<?php class Tests extends CI_Controller { public function getDownload() { $this->load->helper('download'); // load download helper echo "<title> Tutorial And Example </title>"; // Download Helper function for $message = 'Downloading function is easy in CodeIgniter'; *it is the message which reflect on the downloaded file. */ $filename = 'First.txt'; // it takes the filename which you want to show force_download($filename, $message); } } ?>
When you execute the above program in localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/tests/and, it downloads a text file named First.txt, as shown in the following image.
After downloading, click on the downloaded file and open with the notepad editor. It shows the content of the file.
Download Predefined file from the server
You can create a file that can download at run time from the server. To achieve the same, you need to create a Tests.php file in application/controller folder and write the following program.
Tests.php
<?php class Tests extends CI_Controller { public function getDownload() { $this->load->helper('download'); // load download helper echo "<title> Tutorial And Example </title>"; //Here force_download() is used for downloading predefined file in the system force_download('C:/Users/AMIT YADAV/Downloads/CSRF Attack in cakephp Solution.mp4', NULL); } } ?>
When you execute the above program in localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/tests/, it downloads a file that is already exist in local system. We have downloaded a file named CSRF Attack in cakephp Solution.mp4.