views:

39

answers:

2

I have a site with audio files in a mySQL database, all of which are available for playback. That works fine by using the headers:

header("Content-length:". $audioLength);
header("Content-type: ". $audioMime );


echo $audio;

Where the $audioLength and $audioMime are stored with the file in the database and $audio is the actual data.

I now want to add download links for some of the larger files so it would be very obvious to users who don't know how to download an mp3 from a page that they are welcome to do so and put the music on their devices and share them any other way they like. My PHP is the same except I replaced the headers with:

header("Content-type: attachment/octet-stream");
header("Content-disposition: attachment; filename=" . $fileName);

echo $audio;

This still causes Safari and Firefox to play the audio, just in a new window. How do I force a download dialog box? I assume most other browsers out there would play the file as well, so I haven't tested those yet...

M

OK - I'm a blasting idiot!!! I created the PHP file that would download instead of play back from the file that plays back. And I FORGOT TO CHANGE THE REFERENCE TO THE NEW PHP FILE IN THE URL to the files I was retrieving. Brilliant. I had it the first try, it just wasn't working because I was calling the wrong FILE.

So, for any people out there with this question - this is what works:

header('Content-Type: '.$audioMime);
header("Content-disposition: attachment; filename=" . $fileName);

echo $audio;

Ta-da!

Go ahead, laugh at me and give me the idiot of the day badge. I deserve it.

M

+1  A: 

Instead of header("Content-type: attachment/octet-stream");, try using header('Content-Type: application/octet-stream');.

You also might want to add the following header:

header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");

Piro
So, now it looks like this: header('Content-Type: application/octet-stream'); header("Content-disposition: attachment; filename=" . $fileName); header ("Cache-Control: must-revalidate, post-check=0, pre-check=0"); echo $audio;and still plays instead of downloading...
Manca Weeks
cache-control should have no effect at all (when testing things like this of course you should clear the cache before retrying)
Julian Reschke
A: 

1) don't send a different content-type.

2) the unquoted syntax only works if a filename is a token (as defined in MIME), for instance, it can't contain spaces.

In doubt, install LiveHTTPHeaders in Firefox and post what you see on the wire.

Julian Reschke
OK - I changed the content type back. I posted a response to your answer in the main body of the questions because there are not enough chars allowed here...
Manca Weeks
You can add more characters by quoting the filename. You can add even more by using the encoding defined in RFC 2231 and 5987 (but this isn't supported in IE/Safari/Chrome).
Julian Reschke