Getting header response code

2019-02-09 12:37发布

问题:

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!";
        }
    }
}

回答1:

$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!";
}


回答2:

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

var_dump(http_response_code()); // int(200)


回答3:

Here is my solution for people who need send email when server down:

$url = 'http://www.example.com';

while(true) {

    $strHeader = get_headers($url)[0];

    $statusCode = substr($strHeader, 9, 3 );

    if($statusCode != 200 ) {
        echo 'Server down.';
        // Send email 
    }
    else {
        echo 'oK';
    }

    sleep(30);
}


回答4:

You directly returned so function wont execute further foreach condition which you written. Its always better to maintain two functions.

function get_http_response_code($domain1) {
    $headers = get_headers($domain1);
    return substr($headers[0], 9, 3); //**Here you should not return**
    foreach ($get_http_response_code as $gethead) { 
        if ($gethead == 200) {
            echo "OKAY!";
        } else {
            echo "Nokay!";
        }
    }
}


标签: php http