bra*_*ess 23 php webserver curl ping http-status-codes
我想使用PHP检查网站在特定实例中是启动还是关闭.我开始知道curl会获取文件的内容,但我不想阅读网站的内容.我只想查看网站的状态.有没有办法检查网站的状态?我们可以使用ping来检查状态吗?我可以从服务器获取状态信号(404,403等).一小段代码可能对我有很大帮助.
Jef*_*sby 44
这样的事情应该有效
$url = 'yoururl';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (200==$retcode) {
// All's well
} else {
// not so much
}
Run Code Online (Sandbox Code Playgroud)
function checkStatus($url) {
$agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; pt-pt) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";
// initializes curl session
$ch = curl_init();
// sets the URL to fetch
curl_setopt($ch, CURLOPT_URL, $url);
// sets the content of the User-Agent header
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
// make sure you only check the header - taken from the answer above
curl_setopt($ch, CURLOPT_NOBODY, true);
// follow "Location: " redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// disable output verbose information
curl_setopt($ch, CURLOPT_VERBOSE, false);
// max number of seconds to allow cURL function to execute
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// execute
curl_exec($ch);
// get HTTP response code
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode >= 200 && $httpcode < 300)
return true;
else
return false;
}
// how to use
//===================
if ($this->checkStatus("http://www.dineshrabara.in"))
echo "Website is up";
else
echo "Website is down";
exit;
Run Code Online (Sandbox Code Playgroud)
小智 7
curl -Is $url | grep HTTP | cut -d ' ' -f2
Run Code Online (Sandbox Code Playgroud)
你见过get_headers()函数吗?http://it.php.net/manual/en/function.get-headers.php.它似乎完全符合你的需要.
如果直接使用curl -I标志,它将返回HTTP标头(404等)而不是页面HTML.在PHP中,等价物是curl_setopt($ch, CURLOPT_NOBODY, 1);选项.
这是我如何做到的。我设置了用户代理以最大程度地减少目标禁止我的机会并禁用 SSL 验证,因为我知道目标:
private static function checkSite( $url ) {
$useragent = $_SERVER['HTTP_USER_AGENT'];
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // do not return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_USERAGENT => $useragent, // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 2, // timeout on connect (in seconds)
CURLOPT_TIMEOUT => 2, // timeout on response (in seconds)
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false, // SSL verification not required
CURLOPT_SSL_VERIFYHOST => false, // SSL verification not required
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
curl_exec( $ch );
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode == 200);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52548 次 |
| 最近记录: |