Pinging a Website and Retrieving Availability Status in PHP
Determining the availability of a website is a common task in web development. In this article, we will demonstrate how to ping a site and return a boolean representing its availability using PHP.
Solution
The following PHP function, urlExists, effectively pings a URL and returns true if the website is available and false if it is unavailable:
function urlExists($url=NULL) { if($url == NULL) return false; $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $httpcode >= 200 && $httpcode < 300; }
Explanation:
The above is the detailed content of How Can I Use PHP to Check if a Website is Available?. For more information, please follow other related articles on the PHP Chinese website!