PHP Stream mp3 file

2019-07-23 16:49发布

问题:

i need to allow the user to stream it only no download for that file how can i do that ? another question this code i have problem the file get downloaded first then play ?

<?php $file = isset($_GET['q']) ? dirname(__FILE__) . base64_decode($_GET['q']) : false;
$file = urldecode(str_replace('/', '\\', $file));
$download = isset($_GET['d']) ? $_GET['d'] == 't' ? true : false : false;
if ($file) {
$disabelStr = 'DisableTrackDownload-';
$pattern = '/'.$disabelStr.'/';
$disableDownload = preg_match($pattern,$file);
$isFile = is_file($file);
// check if file exists
if($isFile){
    // Getting headers sent by the client.
    $headers = apache_request_headers();
    if(isset($headers['Connection'])){
        // stream audio files
        header("Content-Type: audio/mpeg");
        header('Content-Length:'.filesize($file));
        header('Content-Disposition: inline; filename="stream.file"');
        header('X-Pad: avoid browser bug');
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Expires: -1");
        ob_clean();
        flush();
        readfile($file);
    }else{
        // disable download
        header ("HTTP/1.0 404 Not Found");
    }
    exit;
}
}
?>

回答1:

Part 1: Streaming in general.

An "MP3 stream" is different from a HTTP download. A proper stream requires a streaming media server (e.g. Shoutcast) and is often a transcoded version of a live broadcast or an on-demand version of a large audio file where playback can begin immediately rather than waiting for the whole file to download.

Serving MP3 files via HTTP does not constitute bona-fide "streaming", even if the client (such as Winamp, Quicktime Player, etc) is capable of playing the file before it has downloaded.

To that end, you cannot serve MP3 streams from PHP for reasons that should be obvious (i.e. PHP is a 'short-lived' process and is not meant for long-lifed requests such as streams-over-HTTP).

The scenario you're describing is offering standard HTTP downloads of MP3 files but using clients that can begin playback immediately. Note that owing to how clients work (in general) you cannot stop people from saving a downloaded file.

I suppose you could restrict access to known clients (via the User-agent header) but that's an example of being evil. Please don't do anything like this.


Part 2: Your code

Your PHP code uses the Content-disposition header to hint to the browser that the file should be downloaded to the filesystem rather than the URL passed to an external program or plugin. Remove the header and you'll find that some browsers will launch an MP3 player, but others will still prompt the user to save the file to disk (usually because of user preference, or maybe the lack of an installed MP3 player).

Also, do not use HTTP 404 to deny a request. Use HTTP 403 Forbidden which more accurately describes what you're doing.