我正嘗試在PHP中執行下行帶寬速度測試。我不知道爲什麼wget會以400 Mbps的速度下載1 Mbyte數據,而fsockopen則以170 Mbps的速度下載數據。我使用fsockopen,因爲它在所有服務器上都受支持。fsockopen一般很慢嗎?
有沒有人知道爲什麼? 400 Mbps與170 Mbps是相當大的差異。
是否有更好的性能選擇?
<?php
$url = 'http://ftp.sunet.se/pub/Linux/distributions/ubuntu/ubuntu/dists/hardy-backports/Contents-i386.gz';
$size = 1024*1024; // Get amount of bytes
$parts = parse_url($url);
$fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
if (!$fp) throw new Exception("Problem with $url, $errstr");
$out = "GET " . $parts['path'] ." HTTP/1.1\r\n"
. "Host: ". $parts['host'] ."\r\n"
. "Connection: Close\r\n\r\n";
fwrite($fp, $out);
$found_body = false;
$response = '';
$start = microtime(true);
$timeout = 30;
while (!feof($fp)) {
if ((microtime(true) - $start) > $timeout) break;
if (strlen($response) > $size) break;
//$row = fgets($fp, 128); // Grab block of 128
$row = fgets($fp);
if ($found_body) {
$response .= $row;
} else if ($row == "\r\n") {
$found_body = true;
$tsStart = microtime(true);
continue;
}
}
$time_elapsed = microtime(true) - $tsStart;
$speed = strlen($response)/$time_elapsed * 8/1000000;
echo round($speed, 2) . ' Mbps ('. strlen($response) .' bytes in '. round($time_elapsed, 3) .' s)<br />';
?>
那不支持allow_url_fopen = false – tim
@ user1135440:如果'allow_url_fopen'被設置爲'false',那麼OP將不能以這種方式使用'fopen()'。由於他在抱怨性能,而不是PHP致命錯誤,很明顯他的'allow_url_fopen'沒有設置爲'false'。 – FtDRbwLXw6
allow_url_fopen不適用於fsockopen。 – tim