6

I have written a class that detects if cURL is available, if it is performs GET, POST, DELETE using cURL. In the cURL version I use curl_getinfo($curl, CURLINFO_HTTP_CODE); to get the HTTP code. If is cURL is not available it uses fopen() to read the file contents. How do I get the HTTP header code without cURL?

2
  • If you are reading the HTTP response stream directly then you have to parse out the headers and response code. Not a big deal you should be able to find sample code with a quick search. Commented Mar 15, 2012 at 17:26
  • I've posted some example code in this answer. A more general description how you can do HTTP with PHP w/o the curl functions is outlined in this answer. Commented Mar 15, 2012 at 17:36

2 Answers 2

15

Use get_headers:

<?php
$url = "http://www.example.com/";

$headers = get_headers($url);

$code = $headers[0];
?>

Edit: get_headers requires an additional call, and is not appropriate for this scenario. Use $http_response_headers as suggested by hakre.

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

3 Comments

That will run a request on it's own.
Ah, you would be correct. My answer is likely not the best option in this case.
Well technically it's not wrong, because the TS has not posted much code, so it's actually not clear what exactly she/he wanted to know ;)
8

Whenever you do some HTTP interaction, the special variable $http_response_header on the same scope will contain all headers (incl. the status line header) that are resulted from the last HTTP interaction.

See here for an example how to parse it and obtain the status code.

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.