Werner
Werner

Reputation: 1847

Measure pagespeed "wait" in PHP

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?

Upvotes: 1

Views: 108

Answers (1)

Webdesigner
Webdesigner

Reputation: 1982

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'];

Upvotes: 2

Related Questions