Tail functionality in PHP

Frequently one needs to get the last few lines of some log files, whether php error logs or Apache logs. Most of these file sizes run into megabytes, which makes it difficult and time consuming to remotely open them using ftp. If you have shell access then you can easily use the *nix ‘tail’ command to return the last ‘n’ lines; or one can use the following if shell access is not enabled on your hosting.

function Tail($filename) {
  return system('tail -n 20 '.$filename);

Sometimes even the ‘system’ command is disabled for security reasons, which brings us to the last solution – coding the tail command in PHP. The following is a simple but useful ‘tail’ implementation in PHP. I’ve encapsulated the tail function in a ‘LogRead’ class, which can be further enlarged by adding other useful log functions.

filename = $filename;
    public function tail($lines = 10) 
        $data = '';
        $fp = fopen($this->filename, "r");
        $block = 4096;
        $max = filesize($this->filename);
        for($len = 0; $len < $max; $len += $block) 
            $seekSize = ($max - $len > $block) ? $block : $max - $len;
            fseek($fp, ($len + $seekSize) * -1, SEEK_END);
            $data = fread($fp, $seekSize) . $data;

            if(substr_count($data, "\n") >= $lines + 1) 
                /* Make sure that the last line ends with a '\n' */
                if(substr($data, strlen($data)-1, 1) !== "\n") {
                    $data .= "\n";

                preg_match("!(.*?\n){". $lines ."}$!", $data, $match);
                return $match[0];
        return $data; 

Which you can use as following:


adapted from ‘steve at studio831 dot com’

6 thoughts to “Tail functionality in PHP”

  1. Note that this will only work for files with read access for the current web server user/group. This will most likely limit you to either error and access logs.

  2. What’s most useful with tail is the ‘-f’ option. That’s what is missing here and not that simple with PHP to implement …

Comments are closed.