header - Problem with PHP readfile() dumping binary data to the browser
I trying to force a download by the browser here is my code:
header("Content-Type: application/force-download"); header('Content-type: audio/mp3'); header('Content-Description: File Download'); header('Content-Disposition: attachment; filename=' . $file_name); 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_path); ob_clean(); flush(); readfile($file_path);
This works perfectly on my local machine, but when I upload it to my live server, the binary file is dumped to the browser and those gibberish characters fill up the browser window. What could be the problem? I am on a shared server so I don't know if my apache configuration needs to be changed or something.
I took @sanmi advice and used Firebug to see the response header and here is what I got:
Here is what I got sanmai: Server nginx/0.7.67 Date Tue, 06 Sep 2011 15:02:03 GMT Content-Type text/html; charset=UTF-8 Transfer-Encoding chunked Connection keep-alive Expires Thu, 19 Nov 1981 08:52:00 GMT Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma no-cache Vary Accept-Encoding,User-Agent Content-Encoding gzip
I can see that the content-type entry has changed to text/html, and that the server is actually a nginx one. So is this a nginx issue or are my header entries wrong?
It turns our one of the files I include had a blank line after the closing php tag. That was the problem, thanks everyone for your help.
You send two
Content-Type, only one is necessary.
I am not sure if this might be causing it, but content type audio/mp3 isn't defined(officially): http://www.iana.org/assignments/media-types/audio/index.html . Try using audio/mpeg?
Use FireBug or other means to view HTTP headers your server actually sending. It may hide or alter any of them. If so, talk to your hosting's support.