获取标头响应代码

时间:2010-08-04 17:23:10

标签: php http

这是我整理的PHP脚本的一部分。基本上,域($ domain1)在表单中定义,并根据服务器的响应代码显示不同的消息。但是,我遇到了让它运转的问题。 3位数的响应代码是我感兴趣的。

这是我到目前为止所做的:

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

4 个答案:

答案 0 :(得分:22)

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

答案 1 :(得分:4)

如果你有PHP 5.4.0+,你可以使用 http_response_code() 功能。例如:

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

答案 2 :(得分:1)

以下是我需要在服务器关闭时发送电子邮件的人的解决方案:

$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 :(得分:0)

您直接返回,因此函数不会执行您编写的更多foreach条件。保持两个功能总是更好。

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