是否可以创建一个强制下载文件并回显字符串的 PHP 页面?

Is it possible to create a PHP page that forces a file download and echoes a string?

<?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 脚本。当我加载页面时,我在浏览器中收到下载提示,但页面上没有回显。我试过将 echo 放在 readfile 函数之后,但它不起作用。

你可以玩个小把戏:

<?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_Whosebug.php