Take the 2-minute tour ×

I made a download script which records the time when a user started a download, and then again when the download finishes because I want to be able to check a persons average download speed. For some reason it's not recording the times properly.

I timed a 40ish MB download with a spot watch, which took around 35 seconds but for some reason the script reported it took 181 seconds.

My speed script(just pulls info from database) outputs:

42793248 bytes, downloaded in (1333153897 - 1333153716 =) 181 seconds, so MB/s = 0.22547415211714 (mbytes / time)

I confirmed the bytes & seconds values in my database.

I know the script isn't running for that long, because as soon as I opened the page the download starts(within a second or 2) then when the download finished I checked the database and it was already inserted with these values above.

Here are the more relevent parts of the download script(I think):




$download_id = $_GET['id'];

$traffic = 0;
$started = time();

function headers($r, $h) {
    global $_HEADERSWITCH;
    if (strpos($h,"HTTP/1.1 200")!==false || strpos($h,"HTTP/1.1 206")!==false)
    $_HEADERSWITCH = true;
    return strlen($h);

function bandwidth($r, $d) {
    global $traffic;
    $length = strlen($d);
    $traffic += $length;
    echo $d;
    return $length;

function finish() {
    global $started, $traffic, $download_id;

    $finished = time();

    $sql = "INSERT INTO `downloads`(dlid,traffic,started,finished)
            VALUES ('{$download_id}', '{$traffic}','{$started}','{$finished}')";



And the actual download streaming from server to client:

$dl = curl_init($filelink);
curl_setopt($dl, CURLOPT_HEADERFUNCTION, "headers");
curl_setopt($dl, CURLOPT_WRITEFUNCTION, "bandwidth");
curl_setopt($dl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($dl, CURLOPT_FOLLOWLOCATION, true);

where $filelink = location of the file which I get from my database

Then some code using cURL to forward packets etc to the user whilst recording the traffic used with the bandwidth() function.

Downloads the file fine, records the traffic fine & inserts into the database fine. Only the time's are wrong for some reason.

It really makes no sense to me as to why it records the time wrong as I just call the time() function twice, once when the file is first called upon and once when it finishes.

If you think you need any more info, please let me know.

share|improve this question
how do you stream the file? –  Michal Mar 31 '12 at 3:25
cURL, added it to the main post –  KingHarper Mar 31 '12 at 3:39
add comment


Your Answer



Browse other questions tagged or ask your own question.