display real-time progress and display the loaded files in real-time while loading images using PHP
To display real-time progress and loaded files while loading images using PHP, you can use AJAX and JavaScript to make asynchronous requests to the server and update the UI. Here’s an example implementation: HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Image Loader</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div>
<input type="file" id="image-file" accept="image/*" multiple>
<button id="submit-btn">Upload</button>
<progress id="progress-bar" value="0" max="100"></progress>
</div>
<div id="loaded-files"></div>
<script>
$(document).ready(function() {
$("#submit-btn").click(function() {
var formData = new FormData();
var files = $("#image-file")[0].files;
for (var i = 0; i < files.length; i++) {
formData.append("image[]", files[i]);
}
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
$("#progress-bar").val(percentComplete);
}
}, false);
return xhr;
},
success: function(data) {
$("#loaded-files").html(data);
}
});
});
});
</script>
</body>
</html>
In the HTML code above, we have an input file element to select the images, a button to initiate the upload, a progress bar to show the upload progress, and a div to display the loaded files in real-time.
PHP code (upload.php):
<?php
if (isset($_FILES["image"])) {
$dest_folder = "./images/";
if (!is_dir($dest_folder)) {
mkdir($dest_folder);
}
$uploaded_files = "";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = basename($_FILES["image"]["name"][$key]);
move_uploaded_file($tmp_name, $dest_folder . $name);
$uploaded_files .= "<p>" . $name . " - loaded</p>";
} else {
$name = basename($_FILES["image"]["name"][$key]);
$uploaded_files .= "<p>" . $name . " - failed</p>";
}
}
echo $uploaded_files;
}
?>
In the PHP code above, we receive the uploaded files in the $_FILES superglobal variable, and then loop through each file to move it to the destination folder. We also generate an HTML string to display the loaded files in real-time, and then echo it back to the client.
When you run the HTML file and select some images to upload, you will see the progress bar updating in real-time, and the loaded files being displayed in the “loaded-files” div as they are uploaded.