I am having trouble getting the progress of a file upload using PHP, the server that my site is hosted on is using php v5.6.
I also have the 'uploadprogress' setting enabled in my cpanel manager.
I tried to follow this tutorial: Tracking Upload Progress with PHP and JavaScript
But I merged it with some other code that handles uploading of files using an ajax request.
My form code:
<form id="myForm">
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" id="file" />
<a href="javascript:uploadFile()">Upload</a>
</form>
Upload:
<div id="process">0%</div>
Javascript code: var timer;
function uploadFile() {
var uploadFile = $("#file")[0].files[0];
timer = setInterval(getStatus,1000);
$.ajax(
{
url : "upload.php",
type: 'POST',
data : new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress',
function(e) {
if (e.lengthComputable) {
if (e.loaded < e.total) {
$('#process').html(((e.loaded / e.total) * 100).toFixed(1) + "%");
} else {
$('#process').html("Processing upload, please wait.");
}
}
} , false);
}
return myXhr;
},
success: function (response) {
$('#process').html(response);
clearTimeout(timer);
}
}
);
}
function getStatus() {
$.get("progress.php",
function(response) {
$("#process2").html(response);
}
);
}
upload.php
session_start();
$uploadedFile = $_FILES["file"];
move_uploaded_file($uploadedFile['tmp_name'],$uploadedFile["name"]);
echo $uploadedFile["name"]." was uploaded";
progress.php
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100;
}
Unfortunately in my JS the line: $('#process').html(((e.loaded / e.total) * 100).toFixed(1) + "%");
only gets the time it takes to get the request, not actually upload the file.
I hope I have provided enough information to get some help.