curl and ping - how to check whether a website is either up or down?

后端 未结 7 2167
再見小時候
再見小時候 2020-11-28 12:51

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

7条回答
  •  旧时难觅i
    2020-11-28 13:16

    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);
    }
    

提交回复
热议问题