How can popen() be utilized to monitor the output of a script running on the console in PHP?

To monitor the output of a script running on the console in PHP, you can use the popen() function to open a pipe to the command. This allows you to read the output of the command as it is generated, giving you real-time access to the script's output. You can then process or display this output as needed in your PHP script.

$cmd = 'your_script.sh';
$handle = popen($cmd, 'r');

while (!feof($handle)) {
    $output = fgets($handle);
    echo $output;
    flush(); // Flush the output buffer to display real-time output
}

pclose($handle);