gpt4 book ai didi

javascript - PHP,X-SendFile : Sending file together with outputting text to the browser (via echo)

转载 作者:行者123 更新时间:2023-11-28 15:51:54 25 4
gpt4 key购买 nike

我使用X-SendFile Apache Module从服务器下载大文件。下载效果很好。但是,当下载开始时,我需要向浏览器输出一些文本,例如:“感谢下载文件......”

我的问题是,我无法在一个脚本中同时完成这两件事。我可以下载该文件,然后屏幕上不会输出任何文本。或者,我可以将文本输出到屏幕,但下载脚本将无法启动。

如何在一个 PHP 脚本中完成这两项任务 - 下载文件并将文本内容发送到浏览器/网页?问题可能源于 HTTP 输出 header ,但我不知道如何解决它。

这是我用来通过 X-SendFile 下载文件的示例代码(可以单独正常工作):

header('Content-Description: File Transfer');
header("Content-Disposition: attachment; filename=\"". basename($filePath) . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Length: ' . filesize($filePath));
header("X-Sendfile: $filePath");

为了完成,这是我的测试 echo"" 字符串。如果将其放置在 X-Sendfile 代码上方,则会获得输出,但不会开始下载。如果将其放在 X-Sendfile 代码下方,则会下载文件,但不会向浏览器回显:

echo "SUCCESS!!!";
ob_flush();

约束:

我需要能够通过 URL 轻松下载该文件。例如,www.mydomain.com/?fileID=asl523n53twteHLfga。换句话说,PHP 下载脚本位于 index.php 内。当用户输入 www.mydomain.com 时,将显示域登录页面。但是,当传递附加的 $_GET 变量时,PHP 脚本会识别该变量,并应显示 感谢您下载... 而不是登陆页面。

欢迎提供解决方法。重要的是在保持上述约束的同时达到期望的结果。非常感谢你。

最佳答案

如何添加一个单独的下载页面来下载文件(即 download.php?fileID=XYZ)并让索引页面显示如下消息:

<?php

function homeScreen() {
// your home content
}

function downloadFileScreen ($id) {
?>
<h2>Thank you for your download!</h2>
Your download should start automatically, if it does not, click
<a href="download.php?fileID=<?php print $id; ?>">here</a>
<script type="text/javascript">
window.setTimeout('location.href="download.php?fileID=<?php print $id; ?>"',3000);
</script>
<?php
}

if (isset($_GET['fileID'])) {
$id= $_GET['fileID'];
downloadFileScreen ($id);
?>
} else {
// no ID passed, show home screen
homeScreen();
}
?>

我还没有听说过任何浏览器支持在单个请求中混合下载和 HTTP 内容显示,但我会看看是否可以使用 ob_start() 来实现这一点>ob_flush().

关于javascript - PHP,X-SendFile : Sending file together with outputting text to the browser (via echo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20247293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com