Appearance
Run process with realtime output in PHP
In PHP, you can use the proc_open function to run a process and read its output in real-time. Here is an example of how you can use it:
Example of using proc_open function to run a process and read its output in real-time in PHP
php
<?php
$descriptorspec = [
0 => ["pipe", "r"], // stdin is a pipe that the child will read from
1 => ["pipe", "w"], // stdout is a pipe that the child will write to
2 => ["pipe", "w"], // stderr is a pipe that the child will write to
];
$process = proc_open('echo "Hello World!"', $descriptorspec, $pipes);
if ($process !== false) {
while ($s = fgets($pipes[1])) {
print $s;
}
while ($e = fgets($pipes[2])) {
print $e;
}
proc_close($process);
}
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
This example runs the command echo "Hello World!" and reads its output and error streams in real-time using the fgets function. The output is then printed to the screen. Note that $descriptorspec is an array of descriptor arrays. Each descriptor specifies the pipe type ("r" for read, "w" for write) and the corresponding file descriptor index.