phpapachehttpstdout

Is it possible for a web server to respond to a HTTP request with an extended time stream of output?


When you run PHP scripts in the console, all the standard output text from that script shows up in the console window while the script is running. Is it possible for a browser window to similarly receive status reports in the browser while a lengthy PHP script is running, instead of getting all the output dumped at the conclusion of the script?


Solution

  • Yes. Just call flush() and ob_flush() periodically. It's important to write some output at least every 120 seconds to keep the connection to the browser alive.

    A rough example:

        while(!$done) {
            //doWork();
            echo number_format(100 * ($workDone/$workTotal)) . "% ";
            flush();
            ob_flush();
        }
    

    Edit: here's an arbitrary proof of concept that works in my env:

    print('hello');
    print(str_repeat(".\n", 2048));
    flush();
    //this might be a safe way to only flush the buffer if necessary?
    if(ob_get_length())
        ob_flush();
    sleep(60);