I had a PHP script that relied on shell_exec() and (as a result) worked 99% of the time. The script executed a PhantomJS script that produced an image file. Then using more PHP that image file was processed in a certain way. Problem was that on occasion shell_exec() would hang and cause usability issues. Reading this https://github.com/ariya/phantomjs/issues/11463 I learnt that shell_exec() is the problem and switching to proc_open would solve the hanging.
The problem is that while shell_exec() waits for the executed command to finish proc_open doesn't, and so the PHP commands that follow it and work on the generated image fail as the image is still being produced. I'm working on Windows so pcntl_waitpid is not an option.
My initial approach was to try and get PhantomJS to continuously output something for proc_open to read. You can see what I tried in this thread:
Get PHP proc_open() to read a PhantomJS stream for as long as png is created
I couldn't get this to work and seems no one else has a solution for me. So what I'm asking now is how can I make proc_open work synchronously like shell_exec. I need for the remaining PHP commands in my scripts to be executed only after the proc_open command ends.
Adding my code as per first comment request:
ob_implicit_flush(true);
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$process = proc_open ("c:\phantomjs\phantomjs.exe /test.js", $descriptorspec, $pipes);
if (is_resource($process))
{
while( ! feof($pipes[1]))
{
$return_message = fgets($pipes[1], 1024);
if (strlen($return_message) == 0) break;
echo $return_message.'<br />';
ob_flush();
flush();
}
}
Here is the PhantomJS script:
interval = setInterval(function() {
console.log("x");
}, 250);
var page = require('webpage').create();
var args = require('system').args;
page.open('http://www.cnn.com', function () {
page.render('test.png');
phantom.exit();
});
If instead of "c:\phantomjs\phantomjs.exe /test.js" I use a cmd.exe ping form exmaple I get line after line of $return_message printed, so I know proc_open receives a stream. I'm trying to get the same to happen with the Phantom script.