在 PHP 中解析 HTTP_RANGE 标头 [英] Parsing HTTP_RANGE header in PHP

查看:37
本文介绍了在 PHP 中解析 HTTP_RANGE 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有现有的方法可以在 PHP 中正确解析 HTTP_RANGE 标头?在重新发明轮子之前,我想我会在这里问.

Is there an existing way to parse the HTTP_RANGE header correctly in PHP? Thought I'd ask here before re-inventing the wheel.

我正在使用

preg_match('/bytes=(\d+)-(\d+)/', $_SERVER['HTTP_RANGE'], $matches);

解析标头,但这并没有涵盖标头的所有可能值,所以我想知道是否有一个函数或库可以做到这一点?

to parse the header but that does not cover all possible values of the header so I am wondering if there is a function or library that can do this already?

提前致谢.

推荐答案

而是在发送 416.然后通过在逗号 , 和连字符 - 上爆炸来解析它.我还看到您在正则表达式中使用了 \d+ ,但实际上不需要.当任一范围索引被省略时,它仅表示第一个字节"或最后一个字节".你也应该在你的正则表达式中涵盖它.另请参阅HTTP 规范中的范围标头应该处理它.

Rather use regex to test it before sending a 416. Then just parse it by exploding on the comma , and the hyphen -. I also see that you used \d+ in your regex, but those are actually not required. When either of the range indexes is omitted, then it just means "first byte" or "last byte". You should cover that in your regex as well. Also see the Range header in the HTTP spec how you're supposed to handle it.

开球示例:

if (isset($_SERVER['HTTP_RANGE'])) {
    if (!preg_match('^bytes=\d*-\d*(,\d*-\d*)*$', $_SERVER['HTTP_RANGE'])) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header('Content-Range: bytes */' . filelength); // Required in 416.
        exit;
    }

    $ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
    foreach ($ranges as $range) {
        $parts = explode('-', $range);
        $start = $parts[0]; // If this is empty, this should be 0.
        $end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.

        if ($start > $end) {
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header('Content-Range: bytes */' . filelength); // Required in 416.
            exit;
        }

        // ...
    }
}

$start 必须始终小于 $end

$start must always be less than $end

这篇关于在 PHP 中解析 HTTP_RANGE 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆