popen in php |
Parallel processing in PHP Using popen() Function
Since PHP does not offer native threads, we have to get creative to do parallel processing.
There will be scenarios where PHP takes much time to complete a task. Example scenarios are attaching a large file and and sending an email, or processing a large video file
to make thumbnails. Imagine a user having to wait until PHP finishes the all that job.
All the heavy work might being going on at the server.
But, if a user doesn't see any activity on a page for some time, they might think that the page is not working and leave the page. In such cases, we can make use of a background process.
Example of popen as a Async processing
Make popen as synchronous
The below code will wait until child process completed.
echo date("h:i:s");echo "\n";
$ph = popen('php ' . $commandName , 'r') or die($php_errormsg);
while (! feof($ph)) {
$s = fgets($ph) or die($php_errormsg);
}
pclose($ph) or die($php_errormsg);
echo date("h:i:s");echo "\n";
$ph = popen('php ' . $commandName , 'r') or die($php_errormsg);
while (! feof($ph)) {
$s = fgets($ph) or die($php_errormsg);
}
pclose($ph) or die($php_errormsg);
echo date("h:i:s");echo "\n";