Skip to content

Instantly share code, notes, and snippets.

@wrossmann
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrossmann/7ff9c8486f8317666f4d to your computer and use it in GitHub Desktop.
Save wrossmann/7ff9c8486f8317666f4d to your computer and use it in GitHub Desktop.
This function will read $file backwards, $blocksize bytes at a time, until it finds that it contains at least $lines "\n" characters. It then breaks the buffer into an array of lines, pares out the extras, and returns the data according to the optional arguments $desired_endl and $as_array.
<?php
function get_last_lines($file, $lines, $as_array=false, $desired_endl="\n", $blocksize=1024) {
$buffer = '';
if( ! $fh = fopen($file, 'r') ) { die('could not open file'); }
fseek($fh, ($blocksize * -1) - 1, SEEK_END);
while(true) {
$buffer = fread($fh, $blocksize) . $buffer;
if( preg_match_all("/\n/", $buffer, $trash) > $lines) {
break;
}
$curpos = ftell($fh);
if( $curpos - $blocksize * 2 <= 0 ) {
rewind($fh);
$buffer = fread($fh, $blocksize - $curpos) . $buffer;
break;
}
fseek($fh, $curpos - $blocksize * 2);
}
$b_arr = array_map(function($a){
return preg_replace("/\r\$/", "", $a);
}, explode("\n", $buffer));
$b_arr = array_reverse(array_slice(array_reverse($b_arr), 0, $lines));
if( $as_array ) { return $b_arr; }
else { return implode($desired_endl, $b_arr); }
}
echo get_last_lines('/var/log/messages', 20, false, "\n", 32);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment