Josh Dempsey
Josh Dempsey

Reputation: 253

Asking user to download file in PHP

I am trying to get the browser to prompt the user to download a file. However, after having tried several methods from stack overflow and around the Internet, for some reason all are silently failing. Is it the case that this just isn't possible in modern browsers?

I'm simply wanting the user to download a text (.txt) file from the server. I've tried this code below (and more) to no avail:

header('Content-disposition: attachment; filename=newfile.txt');
header('Content-type: text/plain');
readfile('newfile.txt');

.

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".txt";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

I have tried the examples from PHP.NET (none of which are working for me): http://php.net/manual/en/function.readfile.php

I have the correct permissions set, the file exists and is_readable. I'm now left scratching my head as to why this isn't working. Any help would be great.

Upvotes: 0

Views: 476

Answers (1)

Sourabh Kumar Sharma
Sourabh Kumar Sharma

Reputation: 2807

I have one solution for you.

Lets assume download.php is the file that downloads the file.

So when the user clicks on the link to download show a confirm dialog, if the user selects yes then re direct the user to download.php or else download will not occur some browsers like chrome starts the download without asking users if they like to download a file or not.

Upvotes: 1

Related Questions