views:

58

answers:

2

I have a php script that I have used for years to force downloads from my website. But sometime in the last month or so, it stopped working and is triggering file not found errors. The weird thing is that in firefox, if I do view source on the error page, it is the file I was trying to download. And doing File > Save from there give you the correct file. So I know it's not a problem with the script not finding the file on the server.

Is there something wrong with how I am setting up the headers?

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); 
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: Binary');
header('Content-length: '.filesize($file_url));
header('Content-disposition: attachment; filename="'.basename($file_url).'"');
readfile($file_url);
+1  A: 

Can you try this function?

function force_download($file){
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;   
}
Shubham
Sorry, same result.
unholysampler
Kinda off-topic, what what's up with everybody adding post-check=0 and pre-check=0 when they want to serve files? This is one of those things that doesn't really do anything, and just gets copy-pasted around... https://blogs.msdn.com/b/ie/archive/2006/06/01/613132.aspx
kander
@unholysampler - Are you using chrome browser because I have seen somewhat the same bug in chrome. It fails to render headers.
Shubham
@Shubham - I've tried in FF, IE and Chrome. Firefox is the only one that is set up in a way so that you can do the File > Save thing to get the real file.
unholysampler
A: 

I ended up cheating to make this work.

header("Location: $file_url"); //file_url is now the real url, not the path

And then used cPanel to make sure all the MIME types I was using were set to application/octet-stream.

unholysampler