开发者

Is there a way in PHP to keep a file open and process each line and subsequent lines?

开发者 https://www.devze.com 2022-12-24 12:23 出处:网络
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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消