phpechoforce-download

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.


Solution

  • 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