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 :


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



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
        // add more headers for other content types here
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");

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

        $buffer = fread($fd, 2097152); // 2097152 Octet = 2Mo
        echo $buffer;
fclose ($fd);

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s