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

查看:1697
本文介绍了在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规范的 Range头你应该如何处理吧。

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 must always be less than $end

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

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