I want to check if a site is alive within this cURL code?
I use this code to get a response/result from the other server and I want to know how can I check if the site is alive?
$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dat开发者_Python百科a);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php
All you really have to do is a HEAD
request to see if you get a 200 OK
message after redirects. You do not need to do a full body request for this. In fact, you simply shouldn't.
function check_alive($url, $timeout = 10) {
$ch = curl_init($url);
// Set request options
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => "page-check/1.0"
));
// Execute request
curl_exec($ch);
// Check if an error occurred
if(curl_errno($ch)) {
curl_close($ch);
return false;
}
// Get HTTP response code
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Page is alive if 200 OK is received
return $code === 200;
}
here is the simpler one
<?php
$yourUR="http://sitez.com";
$handles = curl_init($yourUR);
curl_setopt($handles, CURLOPT_NOBODY, true);
curl_exec($handles);
$resultat = curl_getinfo($handles, CURLINFO_HTTP_CODE);
echo $resultat;
?>
Check a web url
status by PHP/cURL function :
Condition is , If HTTP status is not 200
or 302
, or the requests takes longer than 10 seconds
, so the website is unreachable...
<?php
/**
*
* @param string $url URL that must be checked
*/
function url_test( $url ) {
$timeout = 10;
$ch = curl_init();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
$http_respond = curl_exec($ch);
$http_respond = trim( strip_tags( $http_respond ) );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
if ( ( $http_code == 200 ) || ( $http_code == 302 ) ) {
return true;
} else {
// you can return $http_code here if necessary or wanted
return false;
}
curl_close( $ch );
}
// simple usage:
$website = "www.example.com";
if( !url_test( $website ) ) {
echo $website ." is down!";
} else {
echo $website ." functions correctly.";
}
?>
You can try with cURL:
curl -I "<URL>" 2>&1 | awk '/HTTP\// {print $2}'
It will return 200
when it's alive
Keep it short and simple...
$string = @file_get_contents('http://domain.com/curl.php');
If $string
is null
or empty
the page is probably unreachable (or actually doesnt output anything).
精彩评论