CodeIgniter Download File Example (From URL / Server)

CodeIgniter Download File: This tutorial will show you how to download files in codeigniter. Just like uploading files in codeigniter you can download them too - and the PHP framework packs a nice helper function to force file download. You have to use the function force_download() to download file from server and it takes up two parameters, the first one being the name of downloadable file and second one is the file content itself.

Here is the syntax for the said method:


force_download($file_name, $content);

CodeIgniter Download File from URL/Server:

To download file in codeigniter, use the below given function in any of the controller and from the view interface callback the function with a filename you need to download from server.


function download($filename = NULL) {
// load download helder
$this->load->helper('download');
// read file contents
$data = file_get_contents(base_url('/uploads/'.$filename));
force_download($filename, $data);
}

Function file_get_contents() reads the contents of the file into a variable. This step is mandatory if you want to download an existing file from the server.

Then in the view file, add a download button which force file download when it is clicked.


<?php $fname='PHPCookBook.pdf'; ?>
<a href="<?php echo base_url(); ?>/index.php/controller_name/download/<?php echo $fname; ?>">Download PDF</a>
codeigniter-download-file-from-url-server-example

If you keep codeigniter url without index.php then skip the part /index.php from the above href url.

Also Read: CodeIgniter File Upload Example

So, by this way you can download files in codeigniter without hassle. I hope you find this tutorial useful. Keep in touch to get updated with more code igniter tricks.

0 Response to "CodeIgniter Download File Example (From URL / Server)"

Posting Komentar