Monday 22 August 2016

CodeIgniter Download File Example (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.
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.

No comments:

Post a Comment

Installation of Drop Box API on Codigniter

As with the YouTube API the first step in getting this sucker setup is getting a developer key by visiting  https://www.dropbox.com/develop...