Need to refresh the page to see the download

I’m trying to download a simple text file from my server to the client in php. Unfortunately, when i try to download, a new white page appear and the download isn’t ask to the user. But, if i refresh the page, the download is now ask and the user can accept to download the file like usual. Do anyone know why?

P.S. If anyone knows about how not opening another blank page to show the download and just show it on the page i clicked the link, any information would be appreciated.

Here is the code :

HTML

<a href="download.php?download_file=test.txt">Download file</a>

PHP

<?php
ignore_user_abort(true);

set_time_limit(0); // disable the time limit for this script

$path = "toDownload/"; // change the path to fit your websites document structure
$dl_file = $_GET['download_file']; // simple file name validation
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r"))
{
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) 
    {
        case "txt":
        header("Content-type: application/txt");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
        break;
        // add more headers for other content types here
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        break;
    }

    header("Content-length: $fsize");
    header("Cache-control: public"); //use this to open files directly

    while(!feof($fd))
    {
        $buffer = fread($fd, 2097152); // 2097152 Octet = 2Mo
        echo $buffer;
    }
}
fclose ($fd);
exit;
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s