To display the loaded files in real-time and add a progress bar, you will need to use JavaScript and AJAX to update the page dynamically without requiring a full page refresh.
Here’s an example code snippet that shows how to do this:
<?php
// List of URLs
$url_list = array(
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
'https://example.com/image4.jpg',
'https://example.com/image5.jpg',
);
// Destination folder
$dest_folder = './images/';
// Create destination folder if it doesn't exist
if (!is_dir($dest_folder)) {
mkdir($dest_folder);
}
// Loop through each URL and save the image
foreach ($url_list as $key => $url) {
$image_content = file_get_contents($url);
$img = imagecreatefromstring($image_content);
$filename = $dest_folder . basename($url);
imagepng($img, $filename);
imagedestroy($img);
// Send the current progress to the client
$progress = round(($key + 1) * 100 / count($url_list));
echo "<script>updateProgress($progress);</script>";
// Send the list of loaded files to the client
$loaded_files = array_slice($url_list, 0, $key + 1);
echo "<script>updateLoadedFiles(".json_encode($loaded_files).");</script>";
}
?>
Then, you can add the following JavaScript code to your HTML page to display the progress bar and the list of loaded files:
<!DOCTYPE html>
<html>
<head>
<title>Image Loader</title>
<script>
function updateProgress(progress) {
document.getElementById("progress-bar").style.width = progress + "%";
document.getElementById("progress-text").innerHTML = progress + "%";
}
function updateLoadedFiles(files) {
var list = document.getElementById("loaded-files");
list.innerHTML = "";
for (var i = 0; i < files.length; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(files[i]));
list.appendChild(item);
}
}
</script>
<style>
#progress-bar {
background-color: #4CAF50;
width: 0%;
height: 20px;
}
</style>
</head>
<body>
<h1>Image Loader</h1>
<div id="progress-bar-container">
<div id="progress-bar"></div>
</div>
<div id="progress-text">0%</div>
<ul id="loaded-files"></ul>
</body>
</html>
The updateProgress function updates the progress bar and the progress text, while the updateLoadedFiles function updates the list of loaded files. Note that the progress bar style can be customized with CSS.