Created
August 2, 2012 10:57
-
-
Save WillJW/3236234 to your computer and use it in GitHub Desktop.
Upload progress bar with PHP & APC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (isset($_GET['progress_key'])) { | |
$status = apc_fetch('upload_' . $_GET['progress_key']); | |
// Return null if total is empty to avoid divide by zero error below. | |
if (empty($status['total'])) { | |
exit; | |
} | |
echo ($status['current'] / $status['total'] * 100); | |
exit; | |
} | |
if (! isset($_GET['upload_id'])) { | |
exit; | |
} | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
* { margin: 0; padding: 0; } | |
#progress { display: block; width: 0; height: 20px; background: green; } | |
</style> | |
</head> | |
<body> | |
<div id="progress"></div> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script> | |
$(function() { | |
setInterval(function() { | |
$.get('progress.php', { progress_key: <?php echo $_GET['upload_id']; ?>, randval: Math.random() }, function(data) { | |
// Multiple percentage by 2 because the progress bar is 200px wide. | |
$('#progress').css('width', (Math.round(data) * 2) + 'px'); | |
}) | |
}, 1000); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (isset($_FILES['file'])) { | |
// Process file uploads. | |
} | |
$unique_id = uniqid(); | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
iframe { display: none; width: 200px; height: 20px; border: 1px solid black; } | |
</style> | |
</head> | |
<body> | |
<form action="upload.php" method="post" enctype="multipart/form-data"> | |
<p> | |
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $unique_id; ?>"> | |
<input type="file" name="file[]" multiple> | |
<input type="submit" value="Upload"> | |
</p> | |
<iframe frameborder="0" border="0" src="" scrolling="no" scrollbar="no"></iframe> | |
</form> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script> | |
$(function() { | |
$('form').submit(function() { | |
$('iframe').show(); | |
setTimeout(function() { | |
$('iframe').attr('src', 'progress.php?upload_id=<?php echo $unique_id; ?>'); | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment