I want to check whether a website is up or down at a particular instance using PHP. I came to know that curl will fetch the contents of the file but I don\'t want to read th
curl -Is $url | grep HTTP | cut -d ' ' -f2
ping
won't do what you're looking for - it will only tell you if the machine is up (and responding to ping
). That doesn't necessarily mean that the webserver is up, though.
You might want to try using the http_head method - it'll retrieve the headers that the webserver sends back to you. If the server is sending back headers, then you know it's up and running.
You can not test a webserver with ping
, because its a different service. The server may running, but the webserver-daemon may be crashed anyway. So curl is your friend. Just ignore the content.
something like this should work
$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
}
Here is how I did it. I set the user agent to minimize the chance of the target banning me and also disabled SSL verification since I know the target:
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);
}
Have you seen the get_headers() function ? http://it.php.net/manual/en/function.get-headers.php . It seems to do exactly what you need.
If you use curl directly with the -I flag, it will return the HTTP headers (404 etc) instead of the page HTML. In PHP, the equivalent is the curl_setopt($ch, CURLOPT_NOBODY, 1);
option.