Getting header response code

2019-02-09 11:45发布

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

标签: php http
4条回答
三岁会撩人
2楼-- · 2019-02-09 12:27

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);
}
查看更多
女痞
3楼-- · 2019-02-09 12:34

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

var_dump(http_response_code()); // int(200)
查看更多
闹够了就滚
4楼-- · 2019-02-09 12:41
$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!";
}
查看更多
神经病院院长
5楼-- · 2019-02-09 12:43

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!";
        }
    }
}
查看更多
登录 后发表回答