How to measure the download speed and size of a PHP document

Here is what I'm planning: My webpage is a simple filesharing system. I would like to show the download speed for the user. It is not 100%, but it's relative good. And i would like to write the time for downloading... example: your download speed is 300kb/s, you can download this file in 7 seconds..


I have got 2 PHP files.

Alfa file do this:

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

This is simple. I get only one number from the speedtest.php My problem is: I have a variable: (int)$size = 1; I would like to do his: $time_left = $size / $sebesseg; $sebesseg means speed. Download speed in bytes. But I can't use settype, or (int)$sebesseg .. or anything I already know, 'cos it wrotes me an empty variable.. :-( How can I solve this?


Solution 1:

ob_get_clean() will return a string. To obtain the number of bytes write

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

After reading your last comment, I've preapred a short example how a simple download speed measurement script can be done with PHP. The following code should do what you want:

<?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]; 
}

Note that the real download speed can only measured at the client. But the results from the code above should be approximately ok.

Also it would just measure the download size of the HTML page itself. Images. styles and javascripts will extend the real download size of page load. But the speed should be in most cases the same the HTML document.