Skip to content

Instantly share code, notes, and snippets.

@wenbing
Created June 15, 2012 03:31
Show Gist options
  • Save wenbing/2934521 to your computer and use it in GitHub Desktop.
Save wenbing/2934521 to your computer and use it in GitHub Desktop.
tail by php
function tail_read($filename, $lines = 10, $offset = 4096, $onLine = null) {
if(is_callable($lines)) {
$onLine = $lines;
$lines = 10;
$offset = 4096;
}
if(is_callable($offset)) {
$onLine = $offset;
$offset = 4096;
}
$line = $tmp = $remainder = $read = '';
$seek_offset = -$offset;
$fp = fopen($filename, 'r');
while($lines > 0 && fseek($fp, $seek_offset, SEEK_END) === 0) {
$tmp = rtrim(fread($fp, $offset), "\n") . $remainder;
while($lines > 0 && ($pos = strrpos($tmp, "\n")) !== FALSE) {
$line = substr($tmp, $pos + 1);
$flag = is_callable($onLine) ? call_user_func_array($onLine, array($line, &$lines)) : true;
if($flag) {
$read = $line . "\n" . $read;
$lines--;
}
$tmp = substr($tmp, 0, $pos);
}
$remainder = $tmp;
$seek_offset = $seek_offset - $offset;
}
fclose($fp);
return $read;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment