2012-07-14 124 views
1

我需要允许用户流式传输它只有该文件没有下载我该怎么做? 另一个问题,这个代码我有问题的文件首先下载然后播放?PHP Stream mp3文件

<?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; 
} 
} 
?> 

回答

4

Part 1:Streaming in general。

“MP3流”与HTTP下载不同。合适的流需要流媒体服务器(例如Shoutcast),并且通常是现场直播的转码版本或大音频文件的按需版本,其中播放可以立即开始,而不是等待整个文件下载。

即使客户端(如Winamp,Quicktime Player等)能够在下载之前播放文件,通过HTTP服务MP3文件也不构成真正的“流式传输”。

为此,由于原因应该是明显的(即PHP是一个“短命”进程,并不适用于长时间请求,如通过HTTP的流),您无法为PHP提供MP3流。

您描述的场景是提供MP3文件的标准HTTP下载,但使用可立即开始播放的客户端。请注意,由于客户的工作方式(一般而言),您无法阻止用户保存下载的文件。

我想你可以限制访问已知的客户端(通过User-agent标题),但这是一个邪恶的例子。请不要做这样的事情。


第2部分:您的代码

您的PHP代码使用Content-disposition头提示该文件应被下载到文件系统,而不是传递给外部程序或插件的网址浏览器。删除标题,你会发现一些浏览器将启动一个MP3播放器,但其他人仍然会提示用户将文件保存到磁盘(通常是因为用户的喜好,或者可能缺少安装的MP3播放器)。

此外,请勿使用HTTP 404拒绝请求。使用HTTP 403 Forbidden更准确地描述你在做什么。