Search code examples
phpgetguzzle

HTTP Get time for response


I'm playing around with guzzle and trying to build a simple page, that i can add my domains to - and have it check if they are currently online/accessible.

I can currently check if an array/list of domain's is online, or if it gets rejected for some reason. I would love to also be able to see in my log/DB how long it takes from i send a the HTTP request to [mydomain.com] until the response arrives back.

Current Code:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

if(!empty($aDomains))
{       
    $oClient            = new Client(['expect' => false]);
    $aAcceptedResponse  = [];
    $aRejectedResponses = [];
    $aCreatedRequests    = [];
    

    foreach ($aDomains as $iDomainKey => $sDomain) 
    {          
        array_push($aCreatedRequests, new Request('GET', $sDomain));
    }

    $pool = new Pool($oClient, $aCreatedRequests, 
    [
        'concurrency' => 50,
        'options' => ['timeout' => 10],
        'fulfilled'   => function ($response, $index) use (&$aAcceptedResponse) 
        {
            $aAcceptedResponse[] = $index;
        },
        'rejected'    => function ($reason, $index) use(&$aRejectedResponses)  
        {
            $aRejectedResponses[] = $index;
        },
    ]);

    $promise = $pool->promise();
    $promise->wait();
}  

I figured i would be able to find something in the guzzle response object, but so far i have been unable to find anything - am i blind or is it not possible to see this?


Solution

  • Thanks to El_Vanja's answer i figured it out by just using a global timestamp:

        $iStartExecutionTime = microtime(true);
        $oClient             = new Client(['expect' => false]);
        $aAcceptedResponse   = [];
        $aRejectedResponses  = [];
        $aCreatedRequests    = [];      
    
        foreach ($aDomains as $iDomainKey => $oDomain) 
        {          
            array_push($aCreatedRequests, new Request('GET', $oDomain->sDomainName));
            update_domain_uptime_monitor($oDomain->iID, 1, date('Y-m-d H:i:s', strtotime('NOW')+$oDomain->iInterval), date('Y-m-d H:i:s', strtotime('NOW')));
        }
    
        $pool = new Pool($oClient, $aCreatedRequests, 
        [
            'concurrency' => 50,
            'options' => ['timeout' => 10],
            'fulfilled'   => function ($response, $index) use (&$aAcceptedResponse) 
            {               
                $aAcceptedResponse[$index] = (microtime(true)-$GLOBALS['iStartExecutionTime']);
            },
            'rejected'    => function ($reason, $index) use(&$aRejectedResponses)  
            {
                $aRejectedResponses[] = $index;
            },
        ]);
    
        $promise = $pool->promise();
        $promise->wait();