Reputation: 6739
I currently do file upload sequentially with a foreach
loop.Each upload is processed one after the other.
<?php
foreach ($files_array as $file) {
//each image is processed here and upload one after the other
}
?>
However processing multiple images instead of one at a time would be more efficient as the user will wait a lot less.How can i process multiple files at once in php instead of doing it sequentially with a foreach
Upvotes: 3
Views: 2568
Reputation: 17071
You need to fork your process, and fulfill this in few threads. Here my example:
<?php
declare(ticks = 1);
$filesArray = [
'file-0',
'file-1',
'file-2',
'file-3',
'file-4',
'file-5',
'file-6',
'file-7',
'file-8',
'file-9',
];
$maxThreads = 3;
$child = 0;
pcntl_signal(SIGCHLD, function ($signo) {
global $child;
if ($signo === SIGCLD) {
while (($pid = pcntl_wait($signo, WNOHANG)) > 0) {
$signal = pcntl_wexitstatus($signo);
$child--;
}
}
});
foreach ($filesArray as $item) {
while ($child >= $maxThreads) {
sleep(1);
}
$child++;
$pid = pcntl_fork();
if ($pid) {
} else {
// Here your stuff.
sleep(2);
echo posix_getpid()." - $item \n";
exit(0);
}
}
while ($child != 0) {
sleep(3);
}
You can also use queue (for example RabbitMQ or something else).
In your script you can put your job into queue and reply to client that job added to queue and will processed soon. Here you can find detailed example how you can done it with RabbitMQ.
Upvotes: 4
Reputation: 125
You want to upload multiple images at a time ?
If yes so use the "explode" method to upload multiple images.
Upvotes: -2