简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM