'Most optimized way to get http status code of a remote URL

I wrote a twig function to check if an external URL is a valid one, i.e. it returns a HTTP status code 2xx or 3xx :

public function isWorkingUrl($url)
{
    if ($url) {
        try {
            $response = $this->client->request(
                'GET',
                $url
            );
            $response->getHeaders(false);
            $statusCode = $response->getStatusCode();
            
            if ( $statusCode < 200 || $statusCode > 399 ) // 2xx : success, 3xx : redirects
                return false;
            else
                return true;
        } catch (TransportExceptionInterface  $e) {
            return false;
        }
    } else {
        return false;
    }
}

This works fine, but it's very very slow ! If I call this in a loop of 20 URLs I have an ugly timeout error !

Please have a look on the performance for a single URL check : enter image description here

Is there a better way to do this ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source