note 86248 modified in function.fseek by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
read x lines from log file end

marc dot roe at gmail dot com improved a bit speed
but this makes reading even more faster :)

test on my server:
2megs file with his function read elapsed 5 sec vs mines 0.03 sec

faster with large and small file 

<?php
function __file_backread_helper(&$haystack,$needle,$x)
{
	$pos=0;$cnt=0;	
	while( $cnt < $x && ($pos=strpos($haystack,$needle,$pos)) !==false ){$pos++;$cnt++;}	
	return $pos==false ? false:substr($haystack,$pos,strlen($haystack));
}

function file_backread($file,$lines,&$fsize=0){
	$f=fopen($file,'r');
	if(!$f)return Array();
	
	
	$splits=$lines*50;
	if($splits>10000)$splits=10000;

	$fsize=filesize($file);
	$pos=$fsize;
	
	$buff1=Array();
	$cnt=0;

	while($pos)
	{
		$pos=$pos-$splits;
		
		if($pos<0){ $splits+=$pos; $pos=0;}

		fseek($f,$pos);
		$buff=fread($f,$splits);
		if(!$buff)break;
		
		$lines -= substr_count($buff, "\n");

		if($lines <= 0)
		{
			$buff1[] = __file_backread_helper($buff,"\n",abs($lines)+1);
			break;
		}
		$buff1[] = $buff;
	}

	return str_replace("\r",'',implode('',array_reverse($buff1)));
}
?>

end of dirty code

--was--
read x lines from log file end

marc dot roe at gmail dot com improved a bit speed
but this makes reading even more faster :)

test on my server:
2megs file with his function read elapsed 5 sec vs mines 0.03 sec

faster with large and small file 

function __file_backread_helper(&$haystack,$needle,$x)
{
	$pos=0;$cnt=0;	
	while( $cnt < $x && ($pos=strpos($haystack,$needle,$pos)) !==false ){$pos++;$cnt++;}	
	return $pos==false ? false:substr($haystack,$pos,strlen($haystack));
}

function file_backread($file,$lines,&$fsize=0){
	$f=fopen($file,'r');
	if(!$f)return Array();
	
	
	$splits=$lines*50;
	if($splits>10000)$splits=10000;

	$fsize=filesize($file);
	$pos=$fsize;
	
	$buff1=Array();
	$cnt=0;

	while($pos)
	{
		$pos=$pos-$splits;
		
		if($pos<0){ $splits+=$pos; $pos=0;}

		fseek($f,$pos);
		$buff=fread($f,$splits);
		if(!$buff)break;
		
		$lines -= substr_count($buff, "\n");

		if($lines <= 0)
		{
			$buff1[] = __file_backread_helper($buff,"\n",abs($lines)+1);
			break;
		}
		$buff1[] = $buff;
	}

	return str_replace("\r",'',implode('',array_reverse($buff1)));
}

end of dirty code

http://php.net/manual/en/function.fseek.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.