Reputation: 55
I have a database from which I would like the user to download data as a csv file. The user has the option to choose the range of data to be downloaded - namely selected date to current date. I want the csv file to be named as 'selected-date.csv'
I used the following code:
$filename = $date . "csv";
header ('Content-Type:text/csv');
header ('Content-Dispostion: attachment; filename="'.$filename.'"');
The file is downloaded but with the PHP file name(get.php) in which this code resides. I have also tried giving a default file name like "download.csv" but that doesn't work either. No matter what I do the file is downloaded with the php file's name. This is across Chrome, Firefox and IE. I don't have Safari to try it on. The date is in the format YYYY-MM-DD. So I don't think there are any invalid characters that can set off any error.
What am I doing wrong here?
Upvotes: 1
Views: 3484
Reputation: 243
You have to set headers for file download
downloadfile($filename) {
$now = 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: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
//file name
$filename = date("Y-m-d") . ".csv"; // make sure it is .csv ( i can not see . in your case )
//call function
downloadfile($filename);
Upvotes: 2