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.

9 comments:

  1. BRAVO!!! worked perfectly for me.
    i have spend days trying to figure out how to use this download helper to suit my project functionality, am very grateful it has helped me so much. Thank you.

    ReplyDelete
  2. hallo sir, i've got some bug.
    if the file i've been uploaded is 0 byte. i can't download the file, just show blank

    ReplyDelete
  3. do i have to type the $fname always?

    ReplyDelete
  4. do i have to type the $fname always?

    ReplyDelete
  5. sir do i have to change the $fname always?

    ReplyDelete
  6. my file is downloaded but it does not opens properly.
    And I same problem is for image file now what to do?

    ReplyDelete
  7. my file is downloaded but it does not opens properly.
    And I same problem is for image file now what to do?

    ReplyDelete