views:

263

answers:

4

Hello,

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

+4  A: 

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

David Zaslavsky
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.
mjv
A: 

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
Matthew Scharley
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~`
grantwparks
+1  A: 

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

RageZ
+5  A: 

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.

caf
Thanks very much
Brian