用PHP ReadFile的下载()在Firefox,而不是在Chrome

问题描述 投票:0回答:1

我有我的网页上有问题。我建立一个报告工具,下载数据为.csv - 我有一个PHP skript它汇集的数据,并从它生成CSV。所述skript被调用,有exec()命令,详细代码如下。该skript本身使用file_put_contents()生成文件,然后将其保存在我的/ tmp /文件夹,直到其下载的(我在dockerized环境中工作,我们的过滤规则删除下一个请求中的文件,但我可以永久保存文件别的地方,如果这将是neccessary)。我再检查,如果该文件存在与file_exists()并继续调用我的下载功能。在Firefox中,我得到了想要的结果,只有CSV数据的正确内容的文件。

我的主要问题是:当我下载CSV在Chrome中我得到的CSV数据,然后我的网页的HTML源代码 - 所以在CSV数据后的第一线<!doctype html>开始,然后<html lang="de">in TE CSV的下一行等..

让我告诉你一些代码:

在我的脚本:

private function writeToFile($csv)
{
    $fileName = '/path/to/file' '.csv';
    echo "\n" . 'Write file to ' . $fileName . "\n";
    file_put_contents($fileName, $csv);
}

在我的网页类:

    $filePath = '/path/to/finished/csv/'
    exec('php ' . $skriptPath . $skriptParams);
    if (file_exists($filePath)) {
        $this->downloadCsv($filePath);
    } else {
        $pageModel->addMessage(
            new ErrorMessage('Error Text')
        );
    }

在同一个班级我的下载功能:

private function downloadCsv($filePath)
{
    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Content-Length: ' . filesize($filePath));
    readfile($filePath);
}

上面所显示的是工作在Firefox,而不是在Chrome。我已经尝试清除输出缓冲区ob_clean()或发送和ob_end_flush()禁用它,但没有工作了Chrome浏览器。

我也尝试过这样的事情在我的下载功能:

    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');

    $fp =fopen($filePath, 'rw');
    fpassthru($fp);
    fclose($fp);

这将产生在Firefox和Chrome相同的结果 - 我得到的CSV数据,然后将HTML源代码混合到同一个文件。

我是一个Symfony框架内工作,如果这可能是从帮助下,我看到有一些辅助功能,文件下载,但我到目前为止,我无法成功使用它们..

到现在为止我的目标仅仅是获得下载使用Chrome有一个工作MVP能投产 - 这被认为是仅供内部使用,所以我不必在意IE浏览器或其他一些可憎的事,因为我们工作人员被告知使用普通浏览器...但是,当有人看到在一般概念的缺陷随时告诉我!

提前致谢 :)

php google-chrome firefox http-headers output-buffering
1个回答
0
投票

所以我设法得到它的工作,我是在错误的轨道与输出缓冲,但一个简单的exit()after我readfile()was不足以阻止CSV文件结束了HTML的部分。

码:

private function downloadCsv($filePath)
{
    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Content-Length: ' . filesize($filePath));
    readfile($filePath);
    exit;

}
© www.soinside.com 2019 - 2024. All rights reserved.