Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting header response code

Tags:

http

php

This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in.

Here is what I have so far:

function get_http_response_code($domain1) {
    $headers = get_headers($domain1);
    return substr($headers[0], 9, 3);
    foreach ($get_http_response_code as $gethead) { 
        if ($gethead == 200) {
            echo "OKAY!";
        } else {
            echo "Nokay!";
        }
    }
}
like image 980
Batfan Avatar asked Aug 04 '10 17:08

Batfan


People also ask

Is HTTP response code a header?

HTTP headers The status code is just part of the full HTTP response that a server sends to a client. Additional information is sent across with the status code. The full response of a status code plus additional information is called the HTTP header.

How do I find HTTP response code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

How do I get HTTP response in PHP?

For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one. header( "HTTP/1.1 404 Not Found" );

What is the HTTP response header?

A response header is an HTTP header that can be used in an HTTP response and that doesn't relate to the content of the message. Response headers, like Age , Location or Server are used to give a more detailed context of the response.


2 Answers

$domain1 = 'http://google.com';

function get_http_response_code($domain1) {
  $headers = get_headers($domain1);
  return substr($headers[0], 9, 3);
}

$get_http_response_code = get_http_response_code($domain1);

if ( $get_http_response_code == 200 ) {
  echo "OKAY!";
} else {
  echo "Nokay!";
}
like image 111
Mchl Avatar answered Oct 11 '22 21:10

Mchl


If you have PHP 5.4.0+ you can use the http_response_code() function. Example:

var_dump(http_response_code()); // int(200)
like image 37
Andres SK Avatar answered Oct 11 '22 19:10

Andres SK