Skip to content

Instantly share code, notes, and snippets.

@Digiover
Last active January 15, 2022 07:17
Show Gist options
  • Save Digiover/3a616cde4ca41a86a0b7b3b9f7e33fb4 to your computer and use it in GitHub Desktop.
Save Digiover/3a616cde4ca41a86a0b7b3b9f7e33fb4 to your computer and use it in GitHub Desktop.
PHP/cURL function to check a web site status. If HTTP status is not 200 or 302, or the requests takes longer than 10 seconds, the website is unreachable. See https://www.saotn.org/php-curl-check-website-availability/.
<?php
/**
* PHP/cURL function to check a web site status. If HTTP status is not 200 or 302, or
* the requests takes longer than 10 seconds, the website is unreachable.
*
* Follow me on Twitter: @Jan_Reilink
*
* @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 {
// return $http_code;, possible too
return false;
}
curl_close($ch);
}
$website = "www.example.com";
if(!url_test($website)) { echo $website ." is down!"; }
else { echo $website ." functions correctly."; }
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment