![]() |
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* This is the child process, it'll be launched | |
* from the parent process. | |
*/ | |
/* Do some work */ | |
echo "large process is running"; | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo "\n doning the work in Main file\n"; | |
echo date("h:i:s");echo "\n"; | |
$commandName="/var/www/html/main.php"; //Provide full path of the php file | |
$handle = popen('php ' . $commandName , 'r'); | |
echo date("h:i:s"); | |
?> |
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";