TomT Posted June 24, 2016 Share Posted June 24, 2016 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 Quote Link to comment https://forums.phpfreaks.com/topic/301394-reading-file-as-it-changes/ Share on other sites More sharing options...
Jacques1 Posted June 24, 2016 Share Posted June 24, 2016 Why do you want a PHP script? Unix has tail or tailf to do exactly that: tail -f log.txt | grep MATCH The Windows PowerShell has Get-Content with similar features. Quote Link to comment https://forums.phpfreaks.com/topic/301394-reading-file-as-it-changes/#findComment-1534007 Share on other sites More sharing options...
TomT Posted June 26, 2016 Author Share Posted June 26, 2016 Ideally I'd like to do this as a self contained script, not calling any external applications.The code I've got works, but does't display the results one by one.. Quote Link to comment https://forums.phpfreaks.com/topic/301394-reading-file-as-it-changes/#findComment-1534029 Share on other sites More sharing options...
Jacques1 Posted June 26, 2016 Share Posted June 26, 2016 tail and grep are fundamental Unix commands. They're far more basic and efficient than your PHP script. If you insist on reinventing the wheel: fgets() Quote Link to comment https://forums.phpfreaks.com/topic/301394-reading-file-as-it-changes/#findComment-1534030 Share on other sites More sharing options...
TomT Posted June 28, 2016 Author Share Posted June 28, 2016 Thanks using fgets has helped and looks like it could work in this scenario. Quote Link to comment https://forums.phpfreaks.com/topic/301394-reading-file-as-it-changes/#findComment-1534077 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.