Reading Only the Last Five Lines in PHP
Loading an entire file into memory before processing it is a common pattern for small scripts, but it quickly becomes a bottleneck when dealing with log files or data streams that grow indefinitely. The provided example uses fgets inside a while(!feof($fp)) loop to append every line to a single string variable. While this works for tiny files, it forces PHP to read the whole file from start to finish and hold the full text in RAM before you can even inspect the data.
To retrieve only the last five lines of a dynamic file like file.txt, you need to change your reading strategy. Instead of buffering everything, you should maintain a fixed-size buffer in memory. As new lines arrive, you drop the oldest line and make room for the new one. This approach ensures that regardless of whether the file has 100 lines or 10 million lines, your script consumes only enough memory to store five strings.
Using array_slice on File Iteration
The most idiomatic way to achieve this in modern PHP is by iterating over the file handle directly and utilizing built-in array manipulation functions. You can wrap a file pointer in an iterator using new SplFileObject or simply loop through a standard fopen handle, but collecting lines into an array first makes the logic explicit and readable.
Here is a pattern that reads the file line by line into an array, then slices it:
$fp = fopen('file.txt', 'r');
if ($fp === false) {
die("Cannot open file");
}
$lines = [];
while (($line = fgets($fp)) !== false) {
$lines[] = rtrim($line, "\n"); // Optional: remove trailing newlines
}
fclose($fp);
// Check if we have enough lines before slicing
if (count($lines) > 0) {
$lastFive = array_slice($lines, -5);
echo implode("\n", $lastFive);
}
This approach is robust because array_slice with a negative start index automatically calculates the correct position from the end. It handles files with fewer than five lines gracefully, returning whatever data exists rather than throwing an error. However, be aware that this still creates an array containing every line of the file before you extract the subset. If the file is massive, the intermediate array could consume significant memory.
The Circular Buffer Approach for Large Files
If your file.txt is truly huge and streaming into it from another process, holding the entire file history in an array is inefficient. In production scenarios where memory conservation is critical, you should implement a circular buffer logic manually or rely on stream limits.
You can limit the buffer size to exactly five lines during the read loop:
$fp = fopen('file.txt', 'r');
if ($fp === false) {
die("Cannot open file");
}
$maxLines = 5;
$currentLines = [];
while (($line = fgets($fp)) !== false) {
// If we have reached the limit, discard the oldest line (index 0)
if (count($currentLines) >= $maxLines) {
array_shift($currentLines);
}
$currentLines[] = rtrim($line, "\n");
}
fclose($fp);
echo implode("\n", $currentLines);
This method guarantees constant memory usage regardless of file size. Every time the buffer fills up, you remove the first element before adding the new one. This is technically more expensive per line than reading a whole file because of the array_shift operation, which involves moving elements down, but it is the correct trade-off for infinite streams.
Alternative: The tail Command via Shell
Sometimes the cleanest solution isn't in PHP at all. If you are running within a CLI environment or need to pass data to another process, invoking the Unix tail command is often faster and simpler than writing custom buffering logic. You can execute it using exec, shell_exec, or passthru.
$output = shell_exec('tail -n 5 file.txt');
echo $output;
This delegates the heavy lifting to the OS kernel, which is highly optimized for reading from the end of a file. However, this approach relies on system availability and requires appropriate permissions. It also returns raw output including newlines, which you may need to sanitize depending on your application's expectations.
Why Avoid fseek with Text Files
A common misconception is that one can simply seek to the last byte and read backwards. While random access works perfectly for binary files or fixed-record formats like CSV, text files are generally not optimized for seeking from the end in PHP without knowing the exact file size beforehand. Furthermore, reading backwards requires handling variable line lengths, which complicates parsing significantly. Sticking to sequential reads with a sliding window buffer is safer and easier to debug.
For further insights on optimizing file I/O operations in Laravel projects, you might explore resources like https://laravelcompany.com, which often covers best practices for handling large datasets in web applications.