Laravel guzzlehttp - How to check if the host is online?

Viewed 1653

When I try to connect to an offline or non-existent host, I get an exception:

cURL error 6: Could not resolve host: somedomain.com

How do you use these things then? (https://laravel.com/docs/8.x/http-client)

$response->body() : string;
$response->json() : array|mixed;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

I need to know if the host is online / offline.

Edit:

use Illuminate\Support\Facades\Http;
use GuzzleHttp\Exception\RequestException;


public function checkSiteStatus($host)
{
    try {
        return Http::timeout(2)->get($host);
    } catch (RequestException $e) {
        //Access the message or other type of errors and react to them

        if (!$e->hasResponse()) {
            //No response from server. Assume the host is offline or server is overloaded.
            return 'offline';
        }
        
        return 'offline';
    }
}

It doesn't work for me, I always get: cURL error 6: Could not resolve host: somedomain.com

2 Answers

There is a set of Exceptions thrown by Guzzle HTTP Client. It's possible to get a response out of the exceptions.

http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

use GuzzleHttp\Exception\RequestException;

try {
    $client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
    //Access the message or other type of errors and react to them
    $e->getMessage();
    if (! $e->hasResponse()) {
        //No response from server. Assume the host is offline or server is overloaded.
    }
}

If you want to use timeout, then I can provide an option by directing using guzzlehttp.

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


public function checkSiteStatus($host)
{
    define("read_timeout", \GuzzleHttp\RequestOptions::READ_TIMEOUT );
    try {
        $client = new Client();
        $response = $response = $client->get(
                $host, [
                'headers' => [
                    // your headers if any
                ],
                'stream' => true,
                'read_timeout' => 2,
            ]);
        $body = $response->getBody();

       // Returns false on timeout
       $data = $body->read(1024);
       // Returns false on timeout
       $line = fgets($body->detach());
       // you can use $data or $line if they are false means there is timeout.
    } catch (RequestException $e) {
        //Access the message or other type of errors and react to them
    }
}

You can read more about them in docs.

Related