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 &lt;&lt; (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.

5 Responses to “Simple download / upload speed measurement with PHP”

  1. Anil Says:

    Very useful, thanks for sharing.

  2. thorsten Says:

    you are welcome :)

  3. Herod Says:

    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“.

    :)

  4. GH22 Says:

    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.

  5. thorsten Says:

    Can you elaborate? I don’t get your comment.

Leave a Reply