Is there a way in PHP to keep a file open and process each line and subsequent lines?
I want to write a php script that keeps the apache_log file open and "listen" to开发者_开发技巧 the log and deal with each log entry as it happens.
I'm thinking that I need to open a file, get the number of lines, then do this again in a loop - and when the size is different, read the new lines and process them.
Am I barking up the wrong tree, or is there a silly easy solution that I have missed?
Chris
The quick-and-dirty way would be to use tail -f
somehow (assuming it's available):
You could pipe the output in to PHP: tail -f file | php myscript.php
, and then read from php://stdin
.
Or, you could use popen
in the script itself:
$res = popen('tail -f file_name', 'r');
while (!feof($res)) {
$line = fgets($res);
echo $line;
}
The option that comes to my mind would be run script from a cron job every minute or so, and just remember the last line you were on each time.
you should look at php inotify you can have a callback function called each time there is a change on a file you observe. if you opened the file eralier and read all there was, reading again in the file should get you the new content.
精彩评论