Current Location: Home> Latest Articles> 3 Efficient Methods to Read the Last Line of a File in PHP

3 Efficient Methods to Read the Last Line of a File in PHP

gitbox 2025-06-27

What is PHP

PHP (short for Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development and can be embedded into HTML. It has a syntax similar to C, is easy to learn, and supports numerous databases like MySQL, PostgreSQL, and SQLite. PHP is ideal for building dynamic web pages and applications.

Methods to Read the Last Line of a File in PHP

When working with files such as logs or data records, there are several approaches in PHP to efficiently read the last line. Below are three practical solutions.

Reading the Entire File Using file()

The file() function reads the entire file into an array, where each element represents a line from the file:

$lines = file('example.txt');

You can retrieve the last line using end($lines). However, this method loads the entire file into memory, which is not optimal for large files.

Using fseek() and fgets() to Navigate

For larger files, a more memory-efficient way is to use fseek() and fgets() to move the file pointer near the end and read from there:

$file = 'example.txt';
$fp = fopen($file, 'r');
if (!$fp) {
    exit("Can't open file: $file");
}
fseek($fp, -1, SEEK_END);
$newline = fgetc($fp);
if ($newline !== "\n") {
    fseek($fp, -1, SEEK_CUR);
}
while (($char = fgetc($fp)) !== false && $char !== "\n") {
    fseek($fp, -2, SEEK_CUR);
}
$lastLine = fgets($fp);
fclose($fp);

This method is ideal for performance-sensitive environments and allows precise control over the file pointer, especially when the file doesn't end with a newline character.

Using the SplFileObject Class

PHP’s SplFileObject from the Standard PHP Library provides a simpler and more elegant solution for reading the last line:

$file = 'example.txt';
$fileObj = new SplFileObject($file);
$fileObj->seek(PHP_INT_MAX);
$lastLine = $fileObj->current();
$fileObj = null;

This approach avoids the complexity of manually managing file pointers and is both clean and efficient.

Conclusion

Depending on file size and performance requirements, developers can choose from the following options to read the last line of a file in PHP:

  • file(): Simple and straightforward, best for small files.
  • fseek() + fgets(): Offers precise control, suitable for large files.
  • SplFileObject: Clean and efficient, ideal for most use cases.

Mastering these methods will improve your efficiency when working with file operations in PHP, such as log parsing or configuration management.