Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run shell script with live feedback from PHP?

How would I execute a shell script from PHP while giving constant/live feedback to the browser? I understand from the system function documentation:

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

I'm not clear on what they mean by running it as a 'server module'.

Example PHP code:

<?php

system('/var/lib/script_test.sh');

Example shell code:

#!/bin/bash

echo "Start..."
for i in {1..10}
do
        echo "$i..."
        sleep 1
done
echo "Done."

What this does: It will wait about 10 seconds and then flush to the output buffer.

What I want this to do: Flush to the output buffer after each line of output.

like image 542
Highway of Life Avatar asked Feb 19 '26 19:02

Highway of Life


2 Answers

This can be done using popen() which gives you a handle to the stdout of whatever process you open. Chunks of data can be sent to the client using ob_flush(), the data can be displayed using an XHR.

like image 126
rook Avatar answered Feb 24 '26 22:02

rook


One option is to write to a file in the shell script, on each step to say where it's up to. On your web page, use an ajax call every X seconds/minutes. The ajax call will call a PHP script which reads the status file and returns the status or completed steps.

The advantage to this approach is the page live information will be available to multiple visitors, rather than just the one that actually initiated the shell script. Obviously that may or may not be desirable depending on your needs.

The disadvantage of course is the longer the ajax interval, the more out of date the update will be.

like image 32
MrCode Avatar answered Feb 24 '26 22:02

MrCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!