PHP Tail File
Why tail a file?
Sometimes there’s a need to tail log files. This might be to store data in a more structured form, say in a database. Maybe you need to tail al log file to monitor for a certain condition. These log files could be anything, like maybe Apache or Mail logs.
PHP doesn’t come with any easy way built in to tail a file. Unix comes with the handle tail tool. I use tail regularly mixed with a grep, looking for a certain entry which I know will appear.
// tail the apache log only showing line containing the local IP. $ tail -f /var/log/apache.log | grep 127.0.01
Example
// create tail object with a file containing our log data
$tail = new FileTail('/var/log/apache.log');
// if we have a previous position we ran up to restore that position
if (is_file('pos')) {
$tail->setPos(file_get_contents('pos'));
}
// while we can read aline
while ($line = $tail->readLine()) {
// store where we've got to
file_put_contents('pos', $tail->getPos());
// use a regular expression to read values out of the line
....
// use a database connection to store
....
}
This code would run until stopped. With blocking turned on, TailFile will wait and keep checking for newly appended lines.