PHP

Tail Last N Lines of File

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Efficiently read the last N lines of a (possibly large) file by seeking to the end and walking backwards in fixed-size chunks. Avoids loading the entire file into memory.
PHP
Raw
<?php
function tail(string $path, int $lines = 10, int $chunk = 4096): array {
    $fh = fopen($path, 'r');
    if (!$fh) throw new RuntimeException("Cannot open $path");
    fseek($fh, 0, SEEK_END);
    $pos = ftell($fh);
    $buffer = '';
    $found  = 0;
    while ($pos > 0 && $found <= $lines) {
        $read = min($chunk, $pos);
        $pos -= $read;
        fseek($fh, $pos);
        $buffer = fread($fh, $read) . $buffer;
        $found  = substr_count($buffer, "\n");
    }
    fclose($fh);
    $all = explode("\n", rtrim($buffer, "\n"));
    return array_slice($all, -$lines);
}

print_r(tail('/var/log/nginx/access.log', 5));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.