Hey guys, I've wanted to do this in the past but my will power gave out. But this time I was more persistent.
I tried using the code Znupi posted but I couldn't get it to work.
However, I went back to php.net and really read over the different manual pages on the system(), passthru(), exec(), shell_exec() functions and backticks operator.
There is a BIG difference between using the system() or passthru() functions from using any of the others.
This difference is how the output buffers of the command execution are handled.
In system() and passthru(), PHP will attempt to flush the buffers after every line of output.
This means that this code:
will be treated just like this code written in only PHP:
As long as you are not using output buffering on your page (ob_start()) then the effect will be exactly what you are looking for since the buffers will be flushed to the browser after each line of command output.
But of course there is a caveat!
It doesn't work with executing custom shell scripts! (well - not without a small workaround)
The workaround is really simple though. Just use file_get_contents("myscript.sh") to turn the shell script contents into a command string. Insert that command string into your system() command and voila! The output buffers are flushed as expected.
NOTE: One thing I did not test was the effect of this process on the working directory for the execution of the shell script commands. However, if your shell script relies on a particular working directory then make sure that the working directory is either set inside the shell script itself or that you do a "cd /custom/dir/here" (change directory) command just prior to where you insert the shell script command string.
Example: (two files: test.php and test.sh)
$tmp_file = dirname(__FILE__)."/tmp.txt";
$fp = fopen($tmp_file, "w+");
$test_script = file_get_contents("test.sh");
echo \"Doing more...\"
echo "Running test..."
echo "Almost done..."
echo "Test complete."
And for those of you (like me) who are using output buffering on the entire page for whatever reason (templates, caching, error handling) - there is still a little more hacking to do. As long as your output is (X)HTML then the following solution will work for fully output buffered pages (ob_start()).
Separate your system() and passthru() calls into a plain PHP file that just outputs plain text: (obviously make sure that you force some sort of user authentication prior to actually running the commands.php script!)
$script = file_get_contents("script.sh");
then output HTML containing an iFrame:
<iframe src="commands.php" scrolling="auto"></iframe>