首页 > 解决方案 > 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;
  }
}
?>

标签: phpfiledownload

解决方案


问题在于您的标题。尝试这个:

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 中。


推荐阅读