Search code examples
phpperformancemeasurement

PHP: measure TTFB (Time To First Byte)


Since the TTFB can vary by every request, I want to make a statistic and get an average value for it. Does anyone know how I can measure this via PHP? The website bytecheck.com is able to analyze these data: Here is an example with example.com: http://www.bytecheck.com/results?resource=example.com

Does anyone a suggestions how I could achieve something like this?

Thanks in advance.


Solution

  • You can solve this with curl:

    $url = 'https://www.example.com/';
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    
    curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    echo "TTFB of ".$url." is: ".$info['starttransfer_time'];
    

    Result

    TTFB of https://www.example.com/ is: 0.67417