0

The function stream_get_meta_data returns header as an array like this:

Array
(
[timed_out] => 
[blocked] => 1
[eof] => 
[wrapper_data] => Array
    (
        [0] => HTTP/1.1 200 OK

I can get the status with $meta['wrapper_data'][0] but how can I fetch the status code from the value which would be HTTP/1.1 200 OK as explode by HTTP/1.1 is bad idea? Is the only way to use regexp to get the code? If absolutely yes, how is the regexp to get a 3-digits number beginning with 1,2,3,4,5 only?

1
  • Regular expression for this is very simple. /[12345]\d\d/ Commented Aug 2, 2016 at 9:19

2 Answers 2

1

Using explode() seems to be a good idea because the format of the response is always like this by standard.

But you can use a simple regexp to extract this, too:

/[12345]\d\d/
Sign up to request clarification or add additional context in comments.

5 Comments

bad bad idea I meant, is it always HTTP/1.1? what about if this is a different version than 1.1.? I googled and found this trick too: substr($headers[0], 9, 3); is it a better way? or still explode or regext is better?
@user4271704: why ask? It is a simple choice: if your string consists of a fixed substring, and you know there will be a chunk of fixed width after it, substr is all you need. A regex is necessary when you absolutely must grab characters of exact type/class/category some number of times, from 0 to n. BTW, to match a 3-digit number starting with 1 or 2, 3, 4, or 5, you actually need /(?<!\d)[12345]\d\d(?!\d)/. Ahmad, please fix your answer.
I am not good in regexp, please explain what is the difference of your regexp with the one in answer /[12345]\d\d/ ?
And how to get the status message after the code number, e.g. OK, Forbidden etc.? How to parse the entire string to get the message?
This works fine until someone claims HTTP/1.123 or has a 3-digit number in their status description.
0

Since the HTTP wrapper follows redirects by default and that will append several HTTP responses to the wrapper_data array, you both need a stricter regexp that won't trigger on all kinds of headers and to iterate through all lines. And I'd recommend against ignoring statuscodes beginning with 6-9, as there is no way to know how HTTP might evolve in the future. Try this:

$result = array();
foreach ($responsemeta['wrapper_data'] as $headerline) {
    if (preg_match('/^HTTP\/(\d+\.\d+)\s+(\d+)\s*(.+)?$/', $headerline, $result)) {
        $http_version = $result[1];
        $http_statuscode = $result[2];
        $http_statusstring = $result[3];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.