tail/tail.function.php

<?php

/**
 * Tail in PHP, capable of eating big files.
 *
 * @author     Torleif Berger
 * @link       http://www.geekality.net/?p=1654
 * @license    http://creativecommons.org/licenses/by/3.0/
 */
function tail($file, $lines = 10, $buffer = 4096)
{
	if(is_resource($file) && (get_resource_type($file) == 'file' || get_resource_type($file) == 'stream'))
		$f = $file;
	elseif(is_string($file))
		$f = fopen($file, 'rb');
	else
		throw new Exception('$file must be either a resource (file or stream) or a filename.');

	$output = ''; 
	$chunk = '';
	
	fseek($f, -1, SEEK_END);
	
	if(fread($f, 1) != "\n")
		$lines -= 1;

	while(ftell($f) > 0 && $lines >= 0)
	{
		$seek = min(ftell($f), $buffer);
		fseek($f, -$seek, SEEK_CUR);

		$output = ($chunk = fread($f, $seek)).$output;
		fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
		$lines -= substr_count($chunk, "\n");
	}

	while($lines++ < 0)
		$output = substr($output, strpos($output, "\n")+1);

	fclose($f); 
	return $output; 
}