Reputation:
In the following code example, i am calling the download page. However, force_download does not work. There is no redirection, it stays on the same page because of i called the page as index.php/sample/download
. Only the url is changing. But the download is not triggered. Also i can not call the page as direct /sample/download
. Although i specify the required configuration for index.php (index_page), if i do not specify the download link as /sample/index.php/sample/download
, it returns 404 error.
application/controller/Sample.php
class Sample extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url_helper', 'download'));
$this->load->model('Sample_model');
}
public function index() {
$data = $this->getData();
$this->load->view('sample/view', $data);
}
public function download() {
$data = 'Here is some text!';
$name = 'mytext.txt';
force_download($name, $data);
}
}
application/views/sample/view.php
<a href="<?php echo base_url(); ?>index.php/sample/download">Download file</a>
application/config/config.php
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
application/config/routes.php
$route['default_controller'] = 'Sample';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['sample'] = 'sample/index';
$route['sample/download'] = 'sample/download';
Upvotes: 2
Views: 1168
Reputation: 1598
update your codes by following,
application/controller/Sample.php
class Sample extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url_helper', 'download'));
$this->load->model('Sample_model');
}
public function index() {
//$data = $this->getData(); // NOT DEFINED
$this->load->view('sample/view', $data);
}
public function download() {
$data = 'Here is some text!';
$name = 'mytext.txt';
force_download($name, $data);
}
}
application/views/sample/view.php
<a href="<?= base_url('sample/download'); ?>">Download file</a>
application/config/routes.php
$route['default_controller'] = 'sample';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['sample'] = 'sample/index';
$route['sample/download'] = 'sample/download';
make sure your .htaccess
file like same below
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
</IfModule>
Upvotes: 0