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>

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