Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect how long it takes for a file to upload (PHP)

Tags:

php

upload

Is it possible to know (serverside) the time it took for a file to upload? I have an image upload API and in my response I'd like to return the upload time (not including script execution time).

like image 946
makeee Avatar asked May 28 '10 19:05

makeee


2 Answers

I think yes, there is $_SERVER['REQUEST_TIME'] variable that indicates the start of HTTP request, so on the very beginning of your script:

$upload_time = time() - $_SERVER['REQUEST_TIME'];

Result will be in seconds.

like image 86
dev-null-dweller Avatar answered Sep 25 '22 13:09

dev-null-dweller


Seems this method works pretty OK actually:

  1. Send off an ajax request (right before form posts) to the server which stores a session timestamp
  2. Post the form
  3. Check difference in the receiving end :)

HTML

<?php session_start(); // must be at the top ?>

<form id="upload-form" enctype="multipart/form-data" method="post">
    <input type="file" name="datafile" size="40">
    <input type="submit" value="Send">
</form>

<script type="text/javascript">
    $(function()
    {
        $('#upload-form').submit(function()
        {
            $.ajax({
                url: 'start-timer.php',
                type: 'POST',
                context: this,
                success: function() { this.submit(); },
            });

            return false;
        });
    });
</script>

start-timer.php

<?php session_start();
$_SESSION['time'] = microtime(true);

upload.php

<?php 
session_start();
header('content-type: text/plain; charset=utf-8');

if( ! isset($_FILES['file'])
||  ! isset($_SESSION['time'])
||  $_FILES['file']['error'] !== UPLOAD_ERR_OK
||  ! is_uploaded_file($_FILES['file']['tmp_name']))
{
    exit('stuff went wrong...');
}

$time = microtime(true) - $_SESSION['time'];
unset($_SESSION['time']);
echo round($time, 3).'s';

Working sample: http://samples.geekality.net/upload-timer

like image 30
Svish Avatar answered Sep 21 '22 13:09

Svish