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

问题描述 投票:0回答:2
<?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 echo force-download
2个回答
3
投票

你可以玩点小把戏:

<?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


0
投票

2024 年对我有用的解决方案

我知道...我看到了这一年..2016年已经是很久以前的事了。 但也许有更多像我一样的人偶然发现了这个线程,并且解决方案效率低下并且不适合我。所以我把这个分享给你,希望它能帮助别人。

啊,如果现在有更好的方法可以做到这一点。让我知道。

<?php
$file_name = "vcard.vcf";
$file_url = "/usr/share/vcards_contacts/$file_name";

?>
<script type="text/javascript">
window.onload = function(e) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/x-vcard;charset=utf-8,' + encodeURIComponent(`<?php readfile($file_url)?>`));
    pom.setAttribute('download', '<?php echo $file_name ?>');
    pom.click();
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.