PHP 内容处置文件名错误
PHP Content Disposition file name error
我有一个数据库,我希望用户可以从中将数据下载为 csv 文件。用户可以选择要下载的数据范围 - 即所选日期到当前日期。我希望将 csv 文件命名为 'selected-date.csv'
我使用了以下代码:
$filename = $date . "csv";
header ('Content-Type:text/csv');
header ('Content-Dispostion: attachment; filename="'.$filename.'"');
文件已下载,但此代码所在的文件名为 PHP (get.php)。我也尝试过提供默认文件名,例如 "download.csv" ,但这也不起作用。无论我做什么,下载的文件都带有 php 文件名。这涉及 Chrome、Firefox 和 IE。我没有 Safari,无法试用。日期的格式为 YYYY-MM-DD。所以我不认为有任何无效字符可以引发任何错误。
我做错了什么?
您必须设置 headers 才能下载文件
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);
我有一个数据库,我希望用户可以从中将数据下载为 csv 文件。用户可以选择要下载的数据范围 - 即所选日期到当前日期。我希望将 csv 文件命名为 'selected-date.csv'
我使用了以下代码:
$filename = $date . "csv";
header ('Content-Type:text/csv');
header ('Content-Dispostion: attachment; filename="'.$filename.'"');
文件已下载,但此代码所在的文件名为 PHP (get.php)。我也尝试过提供默认文件名,例如 "download.csv" ,但这也不起作用。无论我做什么,下载的文件都带有 php 文件名。这涉及 Chrome、Firefox 和 IE。我没有 Safari,无法试用。日期的格式为 YYYY-MM-DD。所以我不认为有任何无效字符可以引发任何错误。
我做错了什么?
您必须设置 headers 才能下载文件
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);