php tail

September 9, 2009 · Posted in php 

The Problem

You want the functionality of tail(1) in a php function.

The Solution

Bellow is a php function that gives you the last N lines from a file. It doesn't do everything tail(1) does ( like following, retrying, etc ) but just the basic stuff:

function tail($file, $num_to_get=10)
{
        $fp = fopen($file, 'r');
        $position = filesize($file);
        $chunklen = 4096;
        if($position-$chunklen < = 0 )fseek($fp,0);
        else    fseek($fp, $position-$chunklen);
        $data="";$ret="";$lc=0;
        while($chunklen > 0)
        {
                $data = fread($fp, $chunklen);
                $dl=strlen($data);
                for($i=$dl-1;$i>=0;$i--){
                        if($data[$i]=="\n"){
                                if($lc==0 && $ret!="")$lc++;
                                $lc++;
                                if($lc>$num_to_get)return $ret;
                        }
                        $ret=$data[$i].$ret;
                }
                if($position-$chunklen < =0 ){
                        fseek($fp,0);
                        $chunklen=$chunklen-abs($position-$chunklen);
                }else   fseek($fp, $position-$chunklen);
                $position = $position - $chunklen;
        }
        fclose($fp);
        return $ret;
}

It may not be the fastest solution but it works.
Have a better one? Please let me know about it.

Comments

One Comment

Leave a Reply