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?
Asked
Active
Viewed 3.3k times
6

LeeTee
- 6,401
- 16
- 79
- 139
-
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. – Murray McDonald Mar 15 '12 at 17:26
-
I've posted some example code in [this answer](http://stackoverflow.com/a/7566440/367456). A more general description how you can do HTTP with PHP w/o the curl functions is outlined [in this answer](http://stackoverflow.com/a/9705711/367456). – hakre Mar 15 '12 at 17:36
2 Answers
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.

Community
- 1
- 1

Matt Beckman
- 5,022
- 4
- 29
- 42
-
1
-
Ah, you would be correct. My answer is likely not the best option in this case. – Matt Beckman Mar 15 '12 at 18:41
-
2Well 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 ;) – hakre Mar 15 '12 at 19:25
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.