How do I run a shell script with live feedback from PHP?

How can I execute a wrapper script from PHP while providing persistent / forward feedback in the browser? I understand from system :

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

I don't understand what they mean by running it as a "server module".

Sample 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 it does: It will wait for about 10 seconds and then flushed to the output buffer.

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

+3


source to share


2 answers


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



+2


source


One option is to write to a file in a shell script, at each step, to tell you where it is. On your webpage, use an ajax call every X seconds / minutes. The ajax call will invoke a PHP script that reads the status file and returns status or completed steps.

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



Of course the downside is the longer the ajax interval, the more outdated the update will be.

+2


source







All Articles