Jump to content

reading file as it changes ?


TomT

Recommended Posts

Hi

I'm trying to watch a plain text file for any changes.

I want to use PHP and read the file line by line as new lines are added.

Some times 1 line may be added, other times dozens of lines could be added. I want to read each line and check if it matches any keywords..

This is what I've got so far, but it's not line by line... it's buffer size based.

<?php
$file='log.txt';
$line = $lastpos = 0;
while (true) {
    usleep(500000);
    clearstatcache(false, $file);
    $len = filesize($file);
    if ($len < $lastpos) {
        $lastpos = $len;
    }
    elseif ($len > $lastpos) {
        $f = fopen($file, "rb");
        if ($f === false) die();
        fseek($f, $lastpos);
        while (!feof($f)) {
$buffer = fread($f, 4096);
if ($lastpos > 0) {
if (strpos($buffer, 'MATCH') !== false) echo "$line\r\n";
}
            flush();
$line++;
        }
        $lastpos = ftell($f);
        fclose($f);
    }
}
?>

 

Can anyone help point me in the right direction. Ideally I don't want to keep the log in memory as it could grow to a reasonable size.

Thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.