php - PHP脚本下载php文件本身而不是给定的文件
问题描述
我已经问过这个问题,但不正确,而且我不知道,我无法执行 html 页面并在同一页面上开始下载,但现在我知道了。主要问题实际上仍然存在,我无法下载 CSV 文件,它总是获取 PHP 自身。代码被执行。我在 php.ini 中没有找到任何关于 CSV 的信息。我在下载之前直接创建了文件(在另一个页面中),所以它不存在是不可能的。
<?php
if(empty($_POST['checkbox_put_it_in_CSV_too'])!=1){
$file=fopen('created_files/Rankrohad_P_2021-04-01.csv','w');
$filename='created_files/Rankrohad_P_2021-04-01.csv';
foreach($rankrohad as $line){
fputcsv($file,$line,"|","'");
}
fclose($file);
$fsize=filesize($filename);
if(file_exists($filename)){
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content_Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
header('Content-Length: '.$fsize);
readfile($filename);
exit;
}
}
?>
解决方案
问题在于您的标题。尝试这个:
if(file_exists($filename)){
$fsize=filesize($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
header('Content-Length: '.$fsize);
readfile($filename);
exit;
}
在 Content-Disposition 标头中,我转义了文件名,并将文件大小函数放在 IF 中。
推荐阅读
- c# - 如何从 JSON 对象(非数组)中获取 JSON 对象列表(不反序列化)
- android - Android Q - 查询特定文件夹及其子文件夹中的音频文件的 MediaStore
- c++ - 不同版本的 Mac OSX 向后兼容的程度如何?(Xcode C++
- shell - 将相同数据发送到多个动态进程的有效方法
- python - 是否有在python中保存多个具有不同名称的csv文件的功能?
- c++ - 如何正确声明 char8_t 为变音字母?
- python - 正弦回归线与 scipy
- android - 如何使用 Action_SEND 从 Android 中的另一个应用程序启动应用程序?
- histogram - 何时使用 Datadog 分布和直方图
- django - Heroku 上的 Celery、RabbitMQ 和 Django:达到内存限制