How can JavaScript be utilized to handle multiple downloads in PHP?
To handle multiple downloads in PHP using JavaScript, you can create a script that dynamically generates multiple download links based on user input or a predefined list of files. This script can be triggered by a button click or another user action to initiate the downloads.
<?php
// Array of file URLs to download
$files = array(
'file1.pdf',
'file2.jpg',
'file3.zip'
);
// Loop through the array and create download links
foreach ($files as $file) {
echo "<a href='#' onclick='downloadFile(\"$file\")'>$file</a><br>";
}
?>
<script>
function downloadFile(file) {
// Create a hidden anchor element and trigger the download
var downloadLink = document.createElement('a');
downloadLink.href = file;
downloadLink.download = file.split('/').pop();
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
</script>