【问题标题】:PHP return mp3 filePHP 返回 mp3 文件
【发布时间】:2014-08-18 13:45:20
【问题描述】:

我有一个小音乐应用程序,文件从“http://www.mymusicapp.com/get_song.php?name=SOME_MUSIC”之类的 URL 加载。该应用程序在本地运行良好!但是当我将它放在服务器上时,我的应用程序会在浏览器控制台中生成错误。

浏览器错误 未捕获的 InvalidStateError:尝试使用不可用或不再可用的对象

我的 PHP 代码是:

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

  }     

【问题讨论】:

  • 在readfile之前尝试exit检查是否有错误

标签: php error-handling mp3


【解决方案1】:

也许可行:

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

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 2013-12-02
    • 2011-03-31
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2016-12-28
    相关资源
    最近更新 更多