Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get http header response code without cURL

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?

like image 890
LeeTee Avatar asked Mar 15 '12 17:03

LeeTee


2 Answers

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.

like image 185
Matt Beckman Avatar answered Nov 07 '22 09:11

Matt Beckman


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.

like image 23
hakre Avatar answered Nov 07 '22 09:11

hakre