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?

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 Answers2

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
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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836