开发者

Retrieve mp3 from mySQL and force download instead of playback in browser

开发者 https://www.devze.com 2023-01-14 14:00 出处:网络
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:

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-dis开发者_如何学编程position: 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


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");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消