Marius Miskinis
Marius Miskinis

Reputation: 337

PHP: how to handle curl response

Im trying to make script which checks if site is up or down. Everything works fine, but when site is NOT a site, I mean that site does not exist. And then php execution load time increase. I want somehow to handle this. How to check if site doesn't exists and break curl session? Here is my script:

<?php
$ch = curl_init('http://86.100.69.228/'); // e.g. for this will increase execution time because the site doesn't exists
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $status_code;
curl_close($ch);
?>

Upvotes: 1

Views: 817

Answers (2)

Baba
Baba

Reputation: 95161

If you want to check if a site is down CURL might not be the best option since you are not check a full URL such as http://eample.com/abx.phpx ... when you are using services such as "Secured DNS" such as Comodo http://www.comodo.com/secure-dns/ all website would return 200 because request are automatically forwarded for verification so you would always load site with IP address 92.242.144.10 Search 92.242.144.10

My advice is just simply ping the server

function ping($host)
{
    exec(sprintf('ping -n 2 %s', escapeshellarg($host)), $res, $rval);
    return $rval === 0;
}

$result = ping("86.100.69.228");

Out check the socket directly

function pingSocket($host, $port = 80, $timeout = 3) {
    $fsock = fsockopen ( $host, $port, $errno, $errstr, $timeout );
    if (! $fsock) {
        return FALSE;
    } else {
        return TRUE;
    }
}

$result = pingSocket ( "86.100.69.228" );

This works better most times

Upvotes: 1

s.webbandit
s.webbandit

Reputation: 17028

You can define timeout by setting CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT options of cURL transfer in curl_setopt. If site is down cURL will stop working and you'll catch it!

Upvotes: 1

Related Questions