如何衡量PHP文档的下载速度和大小

时间:2013-01-28 17:39:46

标签: php time-measurement ob-get-contents

以下是我的计划:我的网页是一个简单的文件共享系统。我想展示用户的下载速度。它不是100%,而是相对好的。我想写下载的时间......例如:你的下载速度是300kb / s,你可以在7秒内下载这个文件..


我有2个PHP文件。

Alfa文件执行此操作:

ob_start();
require 'speedtest.php';
$sebesseg = ob_get_clean();

这很简单。我只从speedtest.php获得一个数字 我的问题是: 我有一个变量:(int)$size = 1; 我想做他的:$time_left = $size / $sebesseg; $sebesseg表示速度。以字节为单位下载速度但我不能使用settype,或(int)$sebesseg ..或我已经知道的任何东西,'因为它给我一个空变量.. :-( 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

ob_get_clean()将返回一个字符串。获取写入的字节数

$sebesseg = ob_get_clean();
$numberOfBytes = strlen($sebesseg);

在阅读完最后一条评论后,我已经简单介绍了如何使用PHP完成简单的下载速度测量脚本。以下代码应该执行您想要的操作:

<?php
// get the start time as UNIX timestamp (in millis, as float)
$tstart = microtime(TRUE);

// start outout buffering
ob_start();

// display your page
include 'some-page.php';

// get the number of bytes in buffer
$bytesWritten = ob_get_length();

// flush the buffer
ob_end_flush();

// how long did the output take?
$time = microtime(TRUE) - $tstart;

// convert to bytes per second
$bytesPerSecond = $bytesWritten / $time;

// print the download speed
printf('<br/>You\'ve downloaded %s in %s seconds',
    humanReadable($bytesWritten), $time);
printf('<br/>Your download speed was: %s/s',
    humanReadable($bytesPerSecond));

/**
 * This function is from stackoverflow. I just changed the name
 *
 * http://stackoverflow.com/questions/2510434/php-format-bytes-to-kilobytes-megabytes-gigabytes
 */
function humanReadable($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    //$bytes /= pow(1024, $pow);
    $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
}

请注意,实际下载速度只能在客户端测量。但是上面代码的结果应该是合适的。

此外,它只会测量HTML页面本身的下载大小。图片。样式和javascripts将扩展页面加载的实际下载大小。但速度应该在大多数情况下与HTML文档相同。