gpt4 book ai didi

php - 使用 cURL 处理字节范围请求

转载 作者:行者123 更新时间:2023-11-29 03:34:33 25 4
gpt4 key购买 nike

我目前正在尝试将视频流式传输到 iPhone。我的情况几乎与this相同问题,更具体一点。我正在检索的视频来自不同的网站,因此我无法更改视频的检索方式。

我目前必须将一些数据发布到 URL,然后我将收到视频(如果所有数据均有效)。我目前只是使用 cURL 抓取数据,回显它,并将标题设置为 video/mp4。这在大多数情况下都可以正常工作,但与其他问题一样 - 它不适用于 iPhone。我查了一下,显然发现了这一点。

现在,如果我只是从服务器读取文件就可以了,但不幸的是,情况并非如此,因为我必须将特定数据发布到服务器才能实际检索视频。

我将如何使用 cURL 处理字节范围请求?

最佳答案

我通过简单地从外部源(整个东西)下载视频,打开该数据的流,然后从字节范围请求中打印出请求的字节来解决这个问题。为此,我将答案修改为 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 范围。这种方法不是最好的,但我发现我的外部主机不支持字节范围请求,所以我不可能有更好的方法(除了缓存)。我不会使用这种方法,除非您无法控制您从中下载数据的位置是否处理字节范围请求。

关于php - 使用 cURL 处理字节范围请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com