PrashanD
PrashanD

Reputation: 2764

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);

?>

Above is my PHP script. When I load the page I get the download prompt in the browser but there is no echo on the page. I have tried placing the echo after the readfile function but it does not work.

Upvotes: 0

Views: 423

Answers (2)

JulianW
JulianW

Reputation: 101

Solution that worked for me in 2024

I know... I saw the year.. 2016 is a long time ago. But maybe there is more people out there like me that stumble into this thread, and the solution from is inefficient and didnt work for me. So I 'm sharing this back to you, hoping it helps someone.

Ah, and if there is now yet a better way of doing this. Let me know.

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

Upvotes: 1

Nehal J Wani
Nehal J Wani

Reputation: 16629

You can play a little trick:

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

This will create a anchor element and as soon as the page loads, it will force a file download by using the click event.

Demo: http://main.xfiddle.com/e1a35f80/38950596_stackoverflow.php

Upvotes: 3

Related Questions