Php MP3 流媒体问题

Php MP3 Streaming Issues

当我尝试使用 php 从我的本地服务器流式传输音乐时,我遇到了一个非常奇怪的问题。我有基本的用户名/密码授权检查,以确保用户具有流式传输文件的正确权限。问题在于这些检查。

我正在使用 php 的退出函数,如果用户没有查看文件的权限则中止脚本,并回显以通知用户。退出功能似乎正在中断流式传输,即使它没有执行也是如此。

以下是我的代码的亮点:

    function hasPermission($user,$perm)
    {
        if (!accountHasPermission($user,$perm) )
        {
            echo "<center><a style='color:indianred'>Failed to Authenticate: 1";
            echo "<br><br><a href='javascript:history.back()'>Go Back</a>";

            exit;
        }
    }

    function streamTest()
    {
        $filename = "uploads/path_to_file";

        if(file_exists($filename)){
            header('Content-type: audio/mpeg');
            header('Content-Disposition: filename=' . basename($filename) );
            header('X-Pad: avoid browser bug');
            header('Cache-Control: no-cache');  
            readfile( $filename );
        }else{
            header("HTTP/1.0 404 Not Found");
        }
    }

    hasPermission($_POST["username"],"manageFilesWeb");

    streamTest();
    exit;

如果我在 hasPermission 函数中注释掉 exit 调用,音频将毫无问题地流式传输。使用 chrome,我得到了一个看起来像 this. Of course, the exit function will never get called because I am using an account with the correct permissions. I am 100% sure of this. If the exit function is not commented out, the music file will not stream on chrome and the audio player will look like this 的不错的音频播放器。我尝试了多个 chrome 浏览器,但总是得到相同的结果。但是,无论退出行是否被注释掉,音乐都会在 firefox 浏览器中播放。

我尝试了各种其他选项,例如使用 return、die、if/else,但一切都会给我相同的结果。

我还应该注意到,我一直在对我服务器上的其他所有内容使用 hasPermission 函数,例如上传和下载文件。直到现在它从来没有给我任何问题。我花了好几个小时反复试验才弄清楚退出调用可能是问题所在。

我已经到了完全不知道发生了什么的地步。我已经不得不删除简单的 if/else 检查,因为它们会中断流式传输过程,但我已经到了这样的地步,如果我再删除,我将大大降低安全性。

更新: 我发现了这个问题。授权检查是问题所在。我想在文件传输期间,_POST 数据未定义,导致我的授权检查失败。有没有办法在文件流式传输时获取用户名和密码以避免这种情况?

对于这些经过身份验证的文件服务,请使用受人尊敬的网络服务器的 sendfile 方法,您的 php 应用程序是 运行,也就是说有两个流行的网络服务器,

1.阿帕奇

为 Apache 启用 xsendfile mod 首先使用单独的 login.php

读取用户名和密码
  // login.php
  // session_start & stop life cycle codes
  username = $_POST["username"];
  password = $_POST["password"];
  if(hasPermission(username, password){
     $_SESSION["logined"] = true; // setting a session value for successful authentication
  }
  // login success

然后添加文件php文件为流文件,比如file.php

 //file.php
  if(isset($_SESSION["logined"])){
            $filename = "uploads/path_to_file"; // absolute path to file
            header('Content-type: audio/mpeg');
            header('Content-Disposition: filename=' . basename($filename) );
            header('X-Pad: avoid browser bug');
            header('Cache-Control: no-cache');  
            header('X-Sendfile', $filename);
  }else{
      header("HTTP/1.0 404 Not Found"); // or 401 Unauthorized
  }

2。 Nginx

对于 nginx 服务器的使用,请按照 apache 部分中描述的步骤进行操作,除了将 X-Sendfile 替换为 X-Accel-Redirect,检查 here 以获取与 nginx xsendfile 相关的更多说明。