我正在使用此处的函数流式传输大型(500mb+)mp4文件。这个想法是隐藏视频源,到目前为止它是有效的。
唯一的问题是,在视频完成之前,即使你暂停它,也不可能与网站互动(点击链接等)。此外,你几乎必须关闭选项卡和/或浏览器才能让网站做出响应。似乎可以在另一个浏览器上发出请求,所以我知道服务器本身没有被锁定。
功能如下:
$file = "/home/webtest/videos/720p/video.mp4"; // The media file's location
$fp = @fopen($file, 'rb');
$size = filesize($file); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
$content_type = 'application/octet-stream'; // type
header('Content-Type: '.$content_type);
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])){
$c_start = $start;
$c_end = $end;
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false){
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
if ($range == '-'){
$c_start = $size - substr($range, 1);
} else {
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size){
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
$start = $c_start;
$end = $c_end;
$length = $end - $start + 1;
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
// Notify the client the byte range we'll be outputting
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
// Start buffered download
$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end){
if ($p + $buffer > $end){
$buffer = $end - $p + 1;
}
set_time_limit(0);
echo fread($fp, $buffer);
flush();
}
fclose($fp);
这是标题:
HTTP/1.1 206 Partial Content
Date: Mon, 18 Apr 2016 23:36:59 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Accept-Ranges: 0-203395220
Content-Range: bytes 0-203395219/203395220
Content-Length: 203395220
Connection: close
Content-Type: video/mp4
请求标头
Accept:*/*
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:PHPSESSID=24mf06f150895og6s59b9nfte5
DNT:1
Host:
Range:bytes=0-
Referer:
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36
如果你认为这种方法是不正确或有缺陷的,我绝对愿意接受其他流媒体方法。谢谢
为下载提供服务的请求将会话文件锁定,因此后续请求将被阻止,直到它们自己获得锁定为止。
你所需要做的就是在完成$_SESSION
和fread()
循环之间的某个时刻抛出以下内容:
session_write_close();
http://php.net/manual/en/function.session-write-close.php