0
votes

I run a website which allows users to download mp3 files (of my own creation). I used PHP to deliver the mp3 to the user (renaming the file along the way) directly to their downloads area using the attachment option in the content-disposition header tag. Everything works fine except that the downloaded mp3 file is stripped of all its ID3 tags (and cover artwork)

I have tagged and attached artwork to all the files on the server. I can put a simple link to the files on a webpage and right click - Save as and the file will save with tags intact.

This is the php (which i'm sure has been seen here many times)

if ( file_exists($file) ) {
 header("Pragma: public");
 header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Cache-Control: private",false);
 header("Content-Type: audio/mpeg");
 header('Content-Disposition: attachment; filename="'.$tname.'"');
 header("Content-Transfer-Encoding: binary");
 header("Content-Length: ".@filesize($file));
 set_time_limit(0);
 @readfile($file) OR die("<html><body OnLoad=\"javascript: alert('Unable to read file!');history.back();\" bgcolor=\"#F0F0F0\"></body></html>");
 exit;
} else {
 die("<html><body OnLoad=\"javascript: alert('File not found!');history.back();\" bgcolor=\"#F0F0F0\"></body></html>");
}

Any clues as to why the mp3 tags are being lost

2
I'd bet on mime type handling. Every browser does it a little differently, and the standard audio/mpeg may no behave the same as, for instance, Chrome's audio/mp3. - user1119648
@user1119648 That's nonsense. - Brad

2 Answers

1
votes

PHP doesn't know or care about your ID3 tags. It's actually impossible for your code, as shown, to remove the tags without damaging the file.

However, some version of ID3 tags are stored at the end of the file. If that's what's missing, then you're likely hitting a timeout or buffer size limitation somewhere between PHP and your server configuration.

1
votes

SHUT THE FRONT DOOR

So i opened the downloaded mp3 using a hex editor to compare with a version with tags appearing correctly. My downloaded file (using PHP) had some text added to the beginning of the file, i rapidly recognized this text as debug echo's i had left on, so i commented them out which then left 3 mysterious characters at the beginning which ended up being the Byte Order Mark triplets which are embedded in the php file before the 'PHP' tag. This is invisible when using normal html editors and i had to remove them with a hex editor. Now it works.

I know i'm doing something wrong here. How is echo text and the source file BOM ending up in the file?