Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

apache - Parsing HTTP_RANGE header in PHP

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

I am currently using

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?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Kickoff example:

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

        // ...
    }
}

Edit: $start must always be less than $end


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...