How To watch a file write in PHP?

freddiefujiwara picture freddiefujiwara · Jul 9, 2009 · Viewed 25.2k times · Source

I want to make movement such as the tail command with PHP, but how may watch append to the file?

Answer

Emil H picture Emil H · Jul 9, 2009

I don't believe that there's some magical way to do it. You just have to continuously poll the file size and output any new data. This is actually quite easy, and the only real thing to watch out for is that file sizes and other stat data is cached in php. The solution to this is to call clearstatcache() before outputting any data.

Here's a quick sample, that doesn't include any error handling:

function follow($file)
{
    $size = 0;
    while (true) {
        clearstatcache();
        $currentSize = filesize($file);
        if ($size == $currentSize) {
            usleep(100);
            continue;
        }

        $fh = fopen($file, "r");
        fseek($fh, $size);

        while ($d = fgets($fh)) {
            echo $d;
        }

        fclose($fh);
        $size = $currentSize;
    }
}

follow("file.txt");