Forcing a file download (php)

Soldato
Joined
16 Nov 2003
Posts
9,682
Location
On the pale blue dot
I have a load of data in a mysql table that using a php script I have created reformats it as a csv, the idea being that users can click a link to the script and a download link pops up for them to save the csv to disk.

I've been trawling the interweb for info on how to take my data and force the browser to show the download file dialog. The key seems to be 'header' calls but I can't seem to get it to work. The code so far:

Code:
header("Content-type: text/plain);
header("Content-Disposition: attachment; filename=info.csv");
printf "$data";

Where data is a string of info which makes up the csv content.
 
use print or echo, not printf

also set the content-type to application/octet-stream and let the users OS decide what to do with it.
 
Oooh thanks. Getting closer but not quite there.

Now the save dialog appears but it prompts to save the name of the script e.g. "script.php" and contains a line break and a space (basically the blank page if there was no save dialog). I'll go over my syntax.
 
Hmm now its not working at all even when I go back. Going to force no caching as that's probably causing an issue too. Also was missing a quote in the first line. Current code is:

Code:
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="info.csv"');
echo "$data";

Edit:

Forcing no caching almost fixed it. Still prompting to save it as the script name, but its capturing the data in the saved file.
 
Last edited:
Back
Top Bottom