【问题标题】:PHP-How to solve that Html Page Source is appending to the download filePHP-如何解决 Html 页面源附加到下载文件
【发布时间】:2016-05-11 09:59:24
【问题描述】:

上传后我正在从 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>";

【问题讨论】:

    标签: php download


    【解决方案1】:

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

    所以您需要做的是有两个请求和响应:首先,您输出您的页面和用户需要单击的链接(或 JavaScript 或刷新元标记以自动执行此操作)以下载在第二个请求中提交文件。

    【讨论】:

    • 我刚刚在我的第二段中描述了它:在您的页面中,包含一个链接/按钮(供用户手动单击)或一些 JS 或元标记以触发第二个请求,其中您发送实际文件。
    • 's currenty 我已经包含了一个供用户下载的链接
    • 这里面临的问题是下载页面未打开后。for pdf n txt。但是对于 txt 文件,它会附加 html 页面源
    • 嗯,也许您使用的布局在您尝试发送文件时已经输出?然后您需要修复您的代码,以便在这种情况下不使用布局。
    • 你能更具体地了解你所说的布局是什么意思
    猜你喜欢
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2011-06-12
    相关资源
    最近更新 更多