PHP Upload Progress with PHP 5.2 & APC

I decided it would be a good idea to update PHP to allow me to use the new Alternative PHP Cache hook to get access to current upload file progress.

Sounds good right? = well, it’s much simpler than you would think.

First you’ve got to have PHP 5.2 installed on your system. For me this was easy:

yum update php

Then install apc for php:

yum install php-apc

Now it’s time to enable this hidden upload progress gem….
edit your /etc/php.ini file and add this line to the bottom:

apc.rfc1867 = on

All done? – Great… now we can start playing with the code.

Restart Apache, and get your editor out.

Our upload form will need to add a custom ‘ID’ to the form, which allows APC to pick out that individual file and send back the progress.

We need to add this hidden input to our form:

<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $unique_id?>"/>

With that added… we need to add a script which will get the current status of an individual upload:

<?php
if(isset($_GET['progress_key'])) {
 
  $status = apc_fetch('upload_'.$_GET['progress_key']);
  echo $status['current']/$status['total']*100;
 
}
?>

Now we hook them both up together… simply set the upload button to trigger a javascript like this:

<?php
   $unique_id = uniqid("");
?>
 
function getProgress(){
  GDownloadUrl("getprogress.php?progress_key=<?php echo($unique_id);?>",
               function(percent, responseCode) {
                   document.getElementById("progressinner").style.width = percent+"%";
                   if (percent &lt; 100){
                        setTimeout("getProgress()", 100);
                   }
               });
 
}
 
function startProgress(){
    document.getElementById("progressouter").style.display="block";
    setTimeout("getProgress()", 1000);
}

So, there’s the basics of how to get it going… it’s pretty simple really. For a full, and very good guide, see IBM’s guide.