tags:

views:

279

answers:

3

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

A: 
$handler = fopen('somefile.txt', 'r');

// move you at the end of file
fseek($handler, filesize( ));
// move you at the begining of file
fseek($handler, 0);

And probably you will want to consider a use of stream_get_line

Artem Barger
+3  A: 

I don't believe that there's some magical way to do it. You just have to continously 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 handeling:

<?php

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");
Emil H
A: 

Instead of polling filesize you regular checking the file modification time: filemtime

Hippo
Both requires a stat() call underneath the surface, so it doesn't really matter.
Emil H