How to read line by line in output of system () PHP
Here is the situation: I have a unix program that prints out some lines and does not get interrupted as it listens continuously. Now I would like to output strings to PHP script. I used the system () function, but blocked the rest of the code from running because the unix program does not exit. I am thinking of being able to output the string as soon as the string is output by the unix program in the console. How can I achieve this? Thank.
source to share
Here's an example script that will do the trick for you:
$cmd='/bin/ls -la';
$gs="\n"; // this is the delimiter of each line. use "\r\n" in case of windows ...
$pipesDescr=array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", "/tmp/error.log", "a"), );
$p=proc_open($cmd, $pipesDescr, $pipes);
if ($p)
{
stream_set_blocking($pipes[0],0);
stream_set_blocking($pipes[1],0);
$work=true; $buffer=''; $mode='idle'; $command=''; $idle=0;
while ($work)
{
if ($mode=='idle')
{
if ($command<>'')
{
fwrite($pipes[0],$command."\n");
$command='';
$idle=0;
$speed=500; // microseconds!
}
else
{
$speed=100000; // microseconds !
}
}
$s=fread($pipes[1],1024);
if ($s<>'')
{
$mode='action';
$buffer.=$s;
while (strstr($buffer,$gs))
{
$ex=explode($gs,$buffer,2);
{
$buffer=@$ex[1]; $line=@$ex[0];
// here you can process the line with something ...
print($line."<br/>\n");
//
}
}
$speed=500;
$idle=0;
}
else
{
if (@$idle<1000)
{
$idle++; // did not idled for too long, let still watch intensely for new data
}
else
{
$speed=100000; // it been idle for a while, let not overload the CPU for nothing ...
$mode='idle';
}
}
$status=proc_get_status($p);
if (!$status["running"]) {$work=false;} // if the program has quited, we should do so as well ...
} // end of $work loop
proc_close($p);
}
This example uses proc_open and continues until your process exits, or until you decide to exit. (in this case you must set $ work to false ...)
source to share
A good solution is to use proc_open () as you can work with all pipes. A good approach is shown here: http://codehackit.blogspot.be/2012/04/automating-command-line-scripts-in-php.html
I am thinking about the possibility of the line output after line being output by the unix program to the console.
A simple sentence is a difficult problem. This will require monitoring the output buffer or output log file for changes and then reacting to that. The event is connected. Try working with $proc->on()
to detect things in your output buffer to trigger the callback.
Ref: Correct shell execution in PHP and fooobar.com/questions/1056324 / ...
source to share