Home > Back-end >  Return .mp3 from a separate server as audio file, not raw text
Return .mp3 from a separate server as audio file, not raw text

Time:01-16

I am developing a very humble web app which routes all the requests to get an audio file toward a third party server, where the actual files are stored. In order to do this, I am using the following statement in my PHP code:

echo file_get_contents('https://3rdpartyserver.com/' . $filename);

By testing it, it seems to work properly only for text files. While trying to get an .mp3 file, instead, its content as text is actually displayed (instead of the default HTML audio player, which is displayed if I connect directly to the third party server).

I have also tried to add some headers to the response:

header('Content-type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=' . $filename);

But the resulting behavior is still not what I am looking for.

Might you please suggest me how to solve this issue?

CodePudding user response:

You need to set the Content-Type to audio/mpeg, then write the file to the output buffer.

header("Content-Type: audio/mpeg");
header('Content-Disposition: attachment; filename=' . $filename);

readfile('https://3rdpartyserver.com/' . $filename);
exit;

  • Related