Simple download / upload speed measurement with PHP
Januar 29th, 2013
I was requested on stackoverflow to give a little download measurement script in PHP. Below the displayed page an info about download size and download speed should be displayed. I found the question really interesting. Here comes a short example how I would do this:
<?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]; } |
You should 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.
Mai 22nd, 2013 at 10:43
Very useful, thanks for sharing.
Mai 22nd, 2013 at 10:44
you are welcome
April 5th, 2014 at 08:53
I wanted to comment on your code but then i read further and i saw this: „You should note, that the real download speed can only measured at the client. But the results from the code above should be approximately ok“.
Juni 15th, 2015 at 12:09
First dwnl speed is 3MB/s, latest is 40MB/s.,30MB/s, 15MB/s,5MB/s…..I use 10MB file. Not applicable – too large range.
Juni 16th, 2015 at 01:25
Can you elaborate? I don’t get your comment.