在PHP中解析HTTP_RANGE标头

9 php apache http range http-headers

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

我目前正在使用

preg_match('/bytes=(\d+)-(\d+)/', $_SERVER['HTTP_RANGE'], $matches);
Run Code Online (Sandbox Code Playgroud)

解析标题,但不包括标题的所有可能值,所以我想知道是否有一个功能或库可以做到这一点?

提前致谢.

Bal*_*usC 9

而是在发送之前使用正则表达式来测试416.然后通过爆炸逗号和连字符来解析它.我也看到你在你的正则表达式中使用过,但实际上并不是必需的.当省略任何一个范围索引时,它只是意味着"第一个字节"或"最后一个字节".你应该在你的正则表达式中覆盖它.另请参阅HTTP规范中Range标头,了解如何处理它.,-\d+

开球示例:

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;
        }

        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:$ start必须始终小于$ end

  • [字节范围的RFC规范](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35)也允许使用`bytes = -500`这样的有效请求.最后500个字节的文件.这使得提取范围比在`-`字符上爆炸要复杂一些. (2认同)
  • 这个答案是错误的,当它表示当缺少启动时它应该被视为0.正如Andrew Theis所说,当你看到像bytes = -500这样的东西时,它是对文件结尾的请求,NOT bytes = 0-500 . (2认同)