header - Problem with PHP readfile() dumping binary data to the browser

558

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?

Thanks, Tsega

286

Answer

Solution:

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.

535

Answer

Solution:

Here

header("Content-Type: application/force-download"); 
header('Content-type: audio/mp3');

You send twoContent-Type, only one is necessary.

171

Answer

Solution:

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?

736

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Facebook AppRequests not showing?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.