简体   繁体   中英

PHP return mp3 file

I have a little music app where the files are loaded from a URL like " http://www.mymusicapp.com/get_song.php?name=SOME_MUSIC ". Locally the app works fine! But when I put it on the server my app generate an error in browser console.

Browser error Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

My PHP code is:

 $song_name = $_GET['name'];
 $song_file = "{$_SERVER['DOCUMENT_ROOT']}/assets/musics/{$song_name}.mp3";

 if( file_exists( $song_file ) )
 {
      header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
      header('Content-Length: ' . filesize($song_file));
      header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
      header("Content-Transfer-Encoding: binary");      
      header('X-Pad: avoid browser bug');        
      readfile( $song_file );    

  }     

Maybe that works:

$filename = $_GET['name'];
$real_path = "{$_SERVER['DOCUMENT_ROOT']}/assets/musics/{$filename}.mp3";
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
if(file_exists($real_path)) {
    header('Content-type: {$mime_type}');
    header('Content-length: ' . filesize($real_path));
    header('Content-Disposition: filename="' . $filename . '.mp3"');
    header('X-Pad: avoid browser bug');
    header('Cache-Control: no-cache');
    readfile($real_path);
} else {
    header("HTTP/1.0 404 Not Found");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM