PHP 5.4 File Upload Progress and HTML5 Progress Bars04 Dec 2011
This posts was originally written for using pre release versions of php5.4, now PHP5.4 has been release everything should work as before I haven't tested it. There is probably more choice in ways to install it now.
There was a live demo of this but I couldn't justify the cost of a whole ec2 instance just for this!
The way I have implemented this may be problematic in Chrome/Safari due to Webkit Bug 23933, "XMLHttpRequest doesn't work while submitting a form (useful for progress tracking)" I tested this in firefox (the latest version at the time) and it worked fine. Chrome may or may not work. Let me know how you get on.
Full details of the upload progress implementation can be found the official RFC: https://wiki.php.net/rfc/sessionuploadprogress
In this post I'll describe the basic operation of this feature and describe a quick example of its use.
How it Works
The upload progress functionality stores the current progress in a session variable which can then be queried as required to give the current progress, it requires the use of PHP native sessions. The $_SESSION key is set by the form name and a prefix defined in php.ini
An example of the data stored is shown below:
It is up to the developer how they wish to present this data to the user.
SetupThis functionality is included as standard in PHP 5.4 which can be simply installed from an ubuntu package as discussed in my previous post: /internet/installing-php-5-4-in-ubuntu/
This feature should be enabled by default.
ExampleComplete code can be found on github.
Upload FormThe upload form is standard html file upload form apart from an additional hidden value defining the progress name attribute so the upload can be identified in the session variables later:
In my example I've used the jquery form plugin to make submitting the form using AJAX more simple.
Recieving ScriptIn this example the receiving script needs to do nothing except start a session, I added a var_dump for debugging initially:
Client:The client uses an interval time to get the progress every 200ms and pass it to an HTML5 progress bar.
The server side just echos a json encoded version of the session variable: