PHP下载文件没有下载预期的文件

问题描述

我正在尝试下载已上传到我的 uploads 文件夹中的文件。目录是这样的:

xampp
  > htdocs
     > myProject
        > normal_user
           > displayfile.PHP  <-- my current location
        > uploads
           > myfile.pdf

这是我的 HTML 代码显示文件名的部分:

<tr>
   <td> <?PHP if ($fname != "") {?>
          <a href="?forcedownload=true"> <?PHP echo $fname; ?> </a>  
        <?PHP } else { echo "-"; } ?>
   </td>
</tr>

可以执行下面的下载代码,但它没有下载预期的文件。相反,它会下载带有 file name: uploads:

的 .PHP file type: All Files
    if (isset($_GET['forcedownload'])) {

      $filepath = "M:/xampp/htdocs/myProject/uploads/" . $row_file['f_name']; // return: myfile.pdf

      if (file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: ' . $row_file['f_type']); //return: application/pdf
        header('Content-disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit();
      } else {
        exit();
      }
      
    }

我看过许多教程以及回答与我类似情况的 stackoverflow 问题,但它仍然发生相同的情况。我不知道我错过了什么...请帮忙

解决方法

echo $filepath;

查看这个变量的值。

它可能不应该包含您要下载的文件的名称。