Search code examples
phptagsmp3

Downloading mp3 files using PHP


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


Solution

  • 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?