PHP: Firefox downloads files without extension.

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:


$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");

$f = fopen("php://output", 'w');
fputcsv($f, array_keys(reset($myArrayOfData)));
foreach ($myArrayOfData as $row) {
   fputcsv($f, $row);
echo ob_get_clean();

Unfortunately, there seems to have been a problem with the following line:

header("Content-Disposition: attachment;filename={$filename}");

Apparently, in Firefox, you need to enclose the filename in quotes, like so:

header('Content-Disposition: attachment; filename="' . $filename . '"');

Thankfully, this seems to have fixed the issue.