【问题标题】:Is it possible to create a PHP page that forces a file download and echoes a string?是否可以创建一个强制下载文件并回显字符串的 PHP 页面?
【发布时间】:2016-08-15 06:58:05
【问题描述】:
<?php
include "function.php";

$account = findSomeFile();
$file_url = '/var/www/html/tvconfig/netflix/'.$account.'.zip';
echo $account;

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);

?>

上面是我的 PHP 脚本。当我加载页面时,我在浏览器中收到下载提示,但页面上没有回显。我尝试在 readfile 函数之后放置 echo,但它不起作用。

【问题讨论】:

  • 不行,因为单个http请求只能有单个http响应;下载和回声将是两个响应
  • 如果你想让它有点像那样工作,你可以从一个页面向下载页面发出 AJAX 请求。然后它将下载文件,您将停留在同一页面上。例如,您可以创建另一个 HTML 页面,在其中编写“您的下载已开始”之类的内容,同时向该页面发出 AJAX 请求。
  • 而且在发送回声后,您的标题不会有任何区别
  • @Janno 我在回答中避免使用 AJAX :)

标签: php echo force-download


【解决方案1】:

你可以玩个小把戏:

<?php
$account = "38950596";
$file_url = "$account.json";
echo "Hello Friend!\n";

$fc = file_get_contents($file_url);
?>
<script type="text/javascript">
window.onload = function(e) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent('<?php echo $fc ?>'));
    pom.setAttribute('download', '<?php echo $account ?>');
    pom.click();
}
</script>

这将创建一个锚元素,并在页面加载后立即通过点击事件强制下载文件。

演示:http://main.xfiddle.com/e1a35f80/38950596_stackoverflow.php

【讨论】:

  • 一旦你的文件大于几兆字节,这段代码就会导致你的服务器崩溃,也许客户端也会崩溃……
  • @deceze OP 无论如何都要使用 readfile($file_url);那会有什么不同呢?
  • readfile 直接从磁盘流式传输到输出; file_get_contents 首先将整个文件读入内存。
  • @deceze 啊,我明白了。不知道:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多