Search code examples
phpstreamingjplayer

Stream protected media (located outside of httpdocs) with jPlayer


I have uploaded some sample mp3 files to a directory outside of httpdocs, I have ensured that this is accessible to PHP by configuring open_basedir correctly and tested that this directory is working.

What I would like to do is stream these files via a PHP file as non-authenticated users should never have access to these files. I am currently using jPlayer and expect the setMedia function should look similar to this:

$("#jquery_jplayer").jPlayer("setMedia", { mp3: "stream.php?track=" + id + ".mp3" });

I have tried setting content headers etc in stream.php and it currently looks like this:

$filePath = "../song_files/mp3/";
$fileName = "$_GET[track].mp3";

header("Content-Type: audio/mpeg");
header('Content-Disposition: attachment; filename="'.$fileName.'"');

getFile($filePath + $fileName);

If I load this page directly, the mp3 file downloads and plays fine, but when I use the above javascript, jPlayer doesn't play the track.

I have had a look at this post ( Streaming an MP3 on stdout to Jplayer using PHP ) and it appears the user was trying to achieve exactly what I want, but upon testing the solution I keep running into a problem, all I get is "CURL Failed".

Are there any different methods I can use to achieve this. Pointing me in the right direction would be greatly appreciated.


Solution

  • After searching around some more I have found a solution that is working fine. I used the code from a similar topic ( PHP to protect PDF and DOC )

    I will place the code I used here to help answer the question correctly:

    //check users is loged in and valid for download if not redirect them out
    // YOU NEED TO ADD CODE HERE FOR THAT CHECK
    // array of support file types for download script and there mimetype
    $mimeTypes = array(
        'doc' => 'application/msword',
        'pdf' => 'application/pdf',
    );
    // set the file here (best of using a $_GET[])
    $file = "../documents/file.doc";
    
    // gets the extension of the file to be loaded for searching array above
    $ext = explode('.', $file);
    $ext = end($ext);
    
    // gets the file name to send to the browser to force download of file
    $fileName = explode("/", $file);
    $fileName = end($fileName);
    
    // opens the file for reading and sends headers to browser
    $fp = fopen($file,"r") ;
    header("Content-Type: ".$mimeTypes[$ext]);
    header('Content-Disposition: attachment; filename="'.$fileName.'"');
    
    // reads file and send the raw code to browser     
    while (! feof($fp)) {
        $buff = fread($fp,4096);
        echo $buff;
    }
    // closes file after whe have finished reading it
    fclose($fp);
    </code></pre>