There is a download in CSV feature in my current CodeIgniter project. When a user click the link, it will download a file in CSV. The downloaded CSV file's filename is incorrect once the provided filename in the code has a question mark character. To make things clear, below is the code.
public function download($role = NULL, $id = 0, $eid = 0) {
$this->load->helper('download');
$list = $this->respondent->get_respondents($eid);
$questions = $this->respondent->get_all_questions($eid);
$fp = fopen('php://output', 'w');
$fields = array(
'Timestamp',
'First Name',
'Middle Name',
'Last Name',
);
$fields = array_merge($fields, $questions);
fputcsv($fp, $fields);
foreach ($list as $respondent) {
$respondent_data = array(
$respondent->since,
$respondent->first_name,
$respondent->middle_name,
$respondent->last_name,
);
$query = $this->respondent->get_responses($respondent->rid);
foreach($query as $response) {
array_push($respondent_data, $response->answer, $response->duration);
}
fputcsv($fp, $respondent_data);
}
$data = file_get_contents('php://output');
$name = $this->respondent->get_experiment($respondent->eid)->title.'.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
}
In the line header('Content-Disposition: attachment; filename="'.basename($name).'"');
, once the $name
has a question mark character, downloading the file in Firefox or Chrome browser can't interpret it correctly. Rather than a question mark character, the generated character is an underscore or hyphen, respectively. However, when Safari is used to download, the filename is just fine. Is the problem in the code or the browsers?