php tail

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:

  1. function tail($file, $num_to_get=10)
  2. {
  3. $fp = fopen($file, 'r');
  4. $position = filesize($file);
  5. $chunklen = 4096;
  6. if($position-$chunklen < = 0 )fseek($fp,0);
  7. else fseek($fp, $position-$chunklen);
  8. $data="";$ret="";$lc=0;
  9. while($chunklen > 0)
  10. {
  11. $data = fread($fp, $chunklen);
  12. $dl=strlen($data);
  13. for($i=$dl-1;$i>=0;$i--){
  14. if($data[$i]=="\n"){
  15. if($lc==0 && $ret!="")$lc++;
  16. $lc++;
  17. if($lc>$num_to_get)return $ret;
  18. }
  19. $ret=$data[$i].$ret;
  20. }
  21. if($position-$chunklen < =0 ){
  22. fseek($fp,0);
  23. $chunklen=$chunklen-abs($position-$chunklen);
  24. }else fseek($fp, $position-$chunklen);
  25. $position = $position - $chunklen;
  26. }
  27. fclose($fp);
  28. return $ret;
  29. }

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

One thought on “php tail

Leave a Reply