2017-10-11 31 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