无法使用 PHP 从我的文件夹下载我的文件


Unable to download my files from my folder using PHP

我目前正在使用 localhost 来运行我的页面,目前我正在尝试下载我的用户上传并存储在名为 uploaded_files 的文件夹中

的文件

这是我的下载页面的代码,它不起作用,我不太确定出了什么问题。

<?php
$file = $_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename='"" . basename($file) . "'";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    ob_clean();
    flush();
    readfile("C:'xampp'htdocs'FYPproject'uploaded_files/".$file); //showing the path to the server where the file is to be download
    exit;
} else {
    echo "Download failed";
    echo $file;
}
?>

file_exists()需要接收文件的路径,如果文件名是"test"并且它是"uploaded_files/",所以你需要检查file_exists("uploaded_files/test")。如果您的 php 已经在"FYPproject"文件夹中,则无需传递整个路径。下载文件也是如此,您无需传递整个路径即可readfile().

您正在将带有反斜杠和正斜杠的文件路径传递给 readfile 。即使这不是问题的原因,也应该更改它。将其更改为:

readfile("C:'xampp'htdocs'FYPproject'uploaded_files'".$file);

并非所有浏览器都支持application/force-download所以在这种情况下,请尝试用application/octet-stream替换上面的代码,看看它是否有效