The other day, I came across an extremely annoying issue with Firefox and forced PHP downloads. On Chrome, everything was working fine. The user could click on the button and the file would automatically download, ready-to-open. However, in Firefox, the filename didn’t contain the extension that I had specified in the download script.
This led to a situation where users couldn’t automatically open the file that they had downloaded. Instead, they were being given a file that was basically unknown to their operating system.
The fix.
In my particular scenario, I was using PHP to force the browser into downloading a CSV file. My code looked like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?php
$date = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$date} GMT");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
$filename = 'custom_file_' . date("Y-m-d-His") . '.csv';
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
ob_start();
$f = fopen("php://output", 'w');
fputcsv($f, array_keys(reset($myArrayOfData)));
foreach ($myArrayOfData as $row) {
fputcsv($f, $row);
}
fclose($f);
echo ob_get_clean();
|
Unfortunately, there seems to have been a problem with the following line:
|
<?php
header("Content-Disposition: attachment;filename={$filename}");
|
Apparently, in Firefox, you need to enclose the filename in quotes, like so:
|
<?php
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
Thankfully, this seems to have fixed the issue.
0 comments:
Post a Comment