How To watch a file write in PHP?

2020-01-31 02:23发布

问题:

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

回答1:

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");


回答2:

$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer\n";
    flush();
}
pclose($handle);


回答3:

Checkout php-tail on Google code. It's a 2 file implementation with PHP and Javascript and it has very little overhead in my testing.

It even supports filtering with a grep keyword (useful for ffmpeg which spits out frame rate etc every second).



回答4:

$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



回答5:

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



回答6:

Below is what I adapted from above. Call it periodically with an ajax call and append to your 'holder' (textarea)... Hope this helps... thank you to all of you who contribute to stackoverflow and other such forums!

/* Used by the programming module to output debug.txt */
session_start();
$_SESSION['tailSize'] = filesize("./debugLog.txt");
if($_SESSION['tailPrevSize'] == '' || $_SESSION['tailPrevSize'] > $_SESSION['tailSize'])
{
      $_SESSION['tailPrevSize'] = $_SESSION['tailSize'];
}
$tailDiff = $_SESSION['tailSize'] - $_SESSION['tailPrevSize'];
$_SESSION['tailPrevSize'] = $_SESSION['tailSize'];

/* Include your own security checks (valid user, etc) if required here */

if(!$valid_user) {
   echo "Invalid system mode for this page.";
}
$handle = popen("tail -c ".$tailDiff." ./debugLog.txt 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer";
    flush(); 
}
pclose($handle);


标签: php tail