我通過簡單地下載來自外部源的視頻(整個事情),該數據打開一個流,然後打印出從字節範圍請求所請求的字節的固定這一點。要做到這一點,我修改了答案this answer,所以它只是打開基於我下載的數據流:
function rangeDownload($file)
{
$fp = fopen('php://memory', 'r+');
fwrite($fp, $file);
rewind($fp);
$size = strlen($file);
$length = $size;
$start = 0;
$end = $size - 1;
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');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
$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);
}
此代碼假設傳遞給rangeDownload
參數是數據的字符串。這是使用的例子:
// curl initialization here...
$result = curl_exec($ch);
rangeDownload($result);
的rangeDownload
將處理出呼應的數據,並解析所述HTTP範圍。這種方法是不是最好的,但我發現我的外部主機不支持字節範圍請求,所以我不能做它一個更好的方法(除了可能緩存)。除非您無法控制您是否正在從處理字節範圍請求下載數據的位置,否則我不會使用此方法。