13

I am using PHP to parse the numeric portion of the HTTP status code response. Given a standard "HTTP/1.1 200 OK" response, I'd use:

$data = explode(' ', "HTTP/1.1 200 OK");
$code = $data[1];

I'm not an expert on HTTP. Would I ever encounter a response where the code is not at the position of $data[1] as in the above example? I just want to be sure that this method of delimiting the response code will always work for any response.

Thanks, Brian

1
  • 2
    if your using cURL you could be like: curl_getinfo($ch,CURLINFO_HTTP_CODE); which will return 200 or whatever the http status is. Commented Sep 18, 2009 at 7:20

4 Answers 4

17

When in doubt, check the spec. The spec in this case, for HTTP/1.1, is RFC2616. In Section 6.1, it describes the Status-Line, the first component of a Response, as:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

That is - a single ASCII space (SP) must separate the HTTP-Version and the Status-Code - and if you check the definition of HTTP-Version (in Section 3.1) it cannot include a space, and neither can the Status-Code.

So you are good to go with that code.

Sign up to request clarification or add additional context in comments.

Comments

7

No if the webserver respect the standards doing an explode and caching the second item of the array is fine

if you really wants to be sure use a regular expression

i.e.

preg_match('|HTTP/\d\.\d\s+(\d+)\s+.*|',$subject,$match);
var_dump($match[1]);

Cheers

Comments

6

No, you would never encounter a response (if it's a proper HTTP response) which has a different format. See the HTTP RFC (2616).

1 Comment

See 6.1 Status-Line in both RFC 2616 (http 1.1) and RFC 1945 (http 1.0). They both ensure this 3 parts, space delimited format.
2

No, what you are doing is OK if all you want is the numeric. If however you want the message as well, you'll end up splitting it too, ie.

HTTP/1.1 404 Not Found

1 Comment

To prevent that, I use the optional $limit argument like: $aHttpResp = explode(' ', HttpComm::$headers[0], 3); // HTTP/1.x ccc ~long description of the response~

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.