How can PHP be used to limit the number of simultaneous downloads to prevent memory exhaustion?
When handling multiple file downloads in PHP, it's important to limit the number of simultaneous downloads to prevent memory exhaustion. One way to achieve this is by using a semaphore to control access to a shared resource, such as the number of active downloads. By setting a maximum limit on the number of simultaneous downloads, you can prevent the server from running out of memory.
<?php
$semaphoreKey = ftok(__FILE__, 't');
$semaphore = sem_get($semaphoreKey, 1);
// Attempt to acquire the semaphore
if (sem_acquire($semaphore)) {
// Code for downloading the file goes here
// Release the semaphore when the download is complete
sem_release($semaphore);
} else {
echo "Too many downloads in progress. Please try again later.";
}