Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

logging

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?

like image 674
HyderA Avatar asked Jul 10 '10 11:07

HyderA


1 Answers

You need to loop with sleep:

$file='/home/user/youfile.txt';
$lastpos = 0;
while (true) {
    usleep(300000); //0.3 s
    clearstatcache(false, $file);
    $len = filesize($file);
    if ($len < $lastpos) {
        //file deleted or reset
        $lastpos = $len;
    }
    elseif ($len > $lastpos) {
        $f = fopen($file, "rb");
        if ($f === false)
            die();
        fseek($f, $lastpos);
        while (!feof($f)) {
            $buffer = fread($f, 4096);
            echo $buffer;
            flush();
        }
        $lastpos = ftell($f);
        fclose($f);
    }
}

(tested.. it works)

like image 163
Artefacto Avatar answered Sep 23 '22 14:09

Artefacto