1

I know I could measure the total site loading time for an external url just with something like:

$start_request = time();
file_get_contents($url);
$end_request = time ();
$time_taken = $end_request - $start_request;

But I don't need the total site loading, I want to measure only the server-response-time like it's displayed here in the "wait"-part of the result:

http://www.bytecheck.com/results?resource=https://www.example.com

How can I do this with php?

Werner
  • 1,695
  • 3
  • 21
  • 42
  • 7
    You might want to look at [microtime()](http://php.net/manual/en/function.microtime.php) rather than `time()`. – CD001 Oct 11 '17 at 15:33
  • 2
    Possible duplicate of [How to get server response time using PHP](https://stackoverflow.com/questions/34059737/how-to-get-server-response-time-using-php) – Andrejs Cainikovs Oct 11 '17 at 15:34
  • If you want fine-grained statistics like time to first byte, you'll need to use a lower-level library like [Curl](http://php.net/manual/en/book.curl.php). The `curl_get_info` function will have what you need. – iainn Oct 11 '17 at 15:35
  • 3
    @iainn Typo. It's `curl_getinfo()`. – Andrejs Cainikovs Oct 11 '17 at 15:36
  • @CD001 `microtime()` can't help please read the question completely. – Webdesigner Oct 11 '17 at 16:52
  • @Webdesigner - fair point, missed the fact that it's an _external_ URL – CD001 Oct 12 '17 at 08:44

1 Answers1

2

You can't do this with PHP like so. With time() or microtime() you can only get the complete time that one or more commands took.

You need a tool where you have access to the Network Layer Data. cURL can do this for you, but you have to enable php curl, it if its not already done.

PHP can than take the result and process it.

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if (!curl_errno($ch)) {
  $info = curl_getinfo($ch);
  echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}

// Close handle
curl_close($ch);

You have a bunch of informations in $info like

  • "filetime"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "starttransfer_time"
  • "redirect_time"

The complete list could be found here

The "Wait" time should be the starttransfer_time - pretransfer_time, so in your case you need:

$wait = $info['starttransfer_time'] - $info['pretransfer_time'];
Webdesigner
  • 1,954
  • 1
  • 9
  • 16