PHP: How to read a file live that is constantly being written to

Viewed 16223

I want to read a log file that is constantly being written to. It resides on the same server as the application. The catch is the file gets written to every few seconds, and I basically want to tail the file on the application in real-time.

Is this possible?

6 Answers

Yes, you need to sleep some time in the loop but you don't have to reopen the file. I was just looking for a similar problem. I wanted to read a file that might have been changed since last read.

The problem is that the resource has reached end of file (EOF). And does not continue to read. The solution is to reset the pointer with fseek($fh, ftell($fh)).

A complete program that waits for input in a text file might look like this one:

<?php

$fh = fopen('/var/log/system', 'r');
while (true) {
    $line = fgets($fh);
    if ($line !== false) {
      // show the line or send it via email or to a websocket..
    } else {
        // sleep for 0.1 seconds (or more?)
        usleep(0.1 * 1000000);
        fseek($fh, ftell($fh));
    }
}
<?php

$fp = fopen('/var/log/syslog', 'r');// Read only
while (true) {
    $line = stream_get_line($fp, 1024 * 1024, "\n");// Full line found ? (searches for a line break)
    if ($line === false) {
        usleep(100000);// 100ms
        continue;
    }
    echo 'line:' . $line . PHP_EOL;
}
// -- Code impossible to reach --
// fclose($fp);
Related