Raggaer
Raggaer

Reputation: 3318

PHP save console output

Im trying to save all the output lines from a console to a file the code is not working because what it currently does is

Get the last line from console and write it on the file, and also the file isnt updated until I close the process the console is running-

    $start = exec("cd /ot/forgottenserver && ./tfs", $output);

    $file = fopen("/var/www/public/stream.html", "a+");

    while ($start) 
    {
    fwrite($file, $start."\n");
    }

    fclose($file);

I need to write everytime I get a new line from the console and also update the file while the process is executing.

Upvotes: 0

Views: 223

Answers (1)

Razvan
Razvan

Reputation: 2596

Use popen instead of exec. As opposed to exec (which executes the command and returns only after the process finished), popen returns a pointer to that process which you can use in order to read the output.

$h = popen('cd /ot/forgottenserver && ./tfs', 'r');

if ($h) {
    while (!feof($h)) {
        $buf = fread($h, 1024);

        $fileHandle = fopen("/var/www/public/stream.html", "a+");

        if ($fileHandle) {
            fwrite($fileHandle, $buf);
            fclose($fileHandle);
        }
    }

    pclose($h);
}

Upvotes: 1

Related Questions