2017-10-11 29 views
1

我知道我可以测量总的网站加载时间外部URL只是喜欢的东西:措施的PageSpeed“等待”在PHP

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

但我并不需要总网站的加载,我想只测量服务器响应时间像它在这里显示在结果中的“等待” -part:

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

我怎样才能做到这一点用PHP?

+7

你可能想看看[microtime()](http://php.net/manual/en/function.microtime.php)而不是'时间()'。 – CD001

+2

[如何使用PHP获取服务器响应时间]可能的副本(https://stackoverflow.com/questions/34059737/how-to-get-server-response-time-using-php) –

+0

如果您想要细粒度像第一个字节时间这样的统计信息,您需要使用像[Curl](http://php.net/manual/en/book.curl.php)这样的低级库。 'curl_get_info'函数将会有你所需要的。 – iainn

回答

2

你不能用PHP这样做。使用time()microtime()您只能获得一个或多个命令完成的时间。

您需要一个工具,您可以访问网络层数据。 cURL可以为你做到这一点,但你必须enable php curl,如果它尚未完成。

PHP可以比较结果并处理它。

<?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); 

你有$info一堆信息像

  • “文件时间”
  • “TOTAL_TIME”
  • “namelookup_time”
  • “CONNECT_TIME”
  • “pretransfer_time “
  • ”starttransfer_time“
  • ”redirect_time“

完整的列表可以发现here

”等待“ 时间应该是starttransfer_time - pretransfer_time, 所以你的情况,你需要:

$wait = $info['starttransfer_time'] - $info['pretransfer_time']; 
+0

太好了,非常感谢! – Werner