PHP如何解决Html PageSource附加到下载文件中的问题


PHP-How to solve that Html Page Source is appending to the download file

上传后,我正在从Ftp文件夹下载一个文件。

问题是当我打开txt文件时,它显示了附加文件内容的html页面源

如果我预览图像文件(jpg或jpeg),它显示图像已损坏

如果我打开pdf错误:无法加载pdf文档

请告诉我哪里错了。

这是我的代码:

if (isset($_GET['id']) && basename($_GET['id']) == $_GET['id']) {
    $filename = $_GET['id'];
} else {
    $filename =NULL ;
}
$err = 'Sorry, the file you are requesting is unavailable.';
if (!$filename) {
    // if variable $filename is NULL or false display the message
    echo $err;
} else {
    // define the path to your download folder plus assign the file name
    $path = '/home/devestctrl/public_html/wp-content/uploads/'.$filename;
    // check that file exists and is readable
    if (file_exists($path) && is_readable($path)) {
        // get the file size and send the http headers
        $size = filesize($path);
        header('Content-Type: application/octet-stream');
        header('Content-Type: '.$mime);
        header('Content-Length: '.$size);
        header('Content-Disposition: attachment; filename='.$filename);
        header('Content-Transfer-Encoding: binary');
        // open the file in binary read-only mode
        // display the error messages if the file can´t be opened
        $file = @ fopen($path, 'rb');
        if ($file) {
            // stream the file and exit the script when complete
            fpassthru($file);
            exit();
        } else {
            echo $err;
        }
    } else {
        echo $err;
    }
}

我使用$filename的回声进行了检查;

它在文件中显示输出,而不是在页面中打印。

错误显示:

很抱歉,您请求的文件不可用。

出错后我也可以下载,但在文件中显示了$filename

插入表格:

 echo "<tr><a href='?id=" . $row["FileupName"]. "'>".$row["FileupName"]."</td></tr>";

不能将数据输出到页面并同时下载文件。来自浏览器的一个请求将允许您执行一个响应。此响应通常在浏览器中显示为页面,除非您设置了下载标题,否则浏览器会要求您将响应下载到文件中。

因此,你需要做的是有两个请求和响应:在第一个请求中,你输出你的页面和用户需要点击的链接(或者JavaScript或刷新元标记来自动完成),以便在第二个请求中下载文件。