Read last line from file in PHP

To read the last line from a file in PHP, you can use file pointer manipulation with fseek() and fgetc() to read backwards from the end of the file ?

Example

The following code demonstrates how to read the last line by starting from the end of the file and reading backwards until a newline character is found ?

<?php
$line = '';
$f = fopen('data.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);

// Trim trailing newline characters in the file
while ($char === "<br>" || $char === "\r") {
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}

// Read until the next line of the file begins or the first newline char
while ($char !== false && $char !== "<br>" && $char !== "\r") {
    // Prepend the new character
    $line = $char . $line;
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}

fclose($f);
echo $line;
?>
Last line of the file content will be displayed here

How It Works

The algorithm works by:

  • Opening the file in read mode using fopen()
  • Setting the cursor to −1 and using fseek() with SEEK_END to move to the end of the file
  • Reading backwards character by character using fgetc()
  • Skipping any trailing newline characters
  • Building the last line by prepending each character until another newline is encountered

Alternative Method Using file()

A simpler approach is to use the file() function which reads the entire file into an array ?

<?php
$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lastLine = end($lines);
echo $lastLine;
?>

Conclusion

The first method is memory−efficient for large files as it reads backwards without loading the entire file. The second method is simpler but loads all lines into memory first.

Updated on: 2026-03-15T08:48:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements