Read last line from file in PHP


To read last line from file in PHP, the code is as follows −

$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 === "
" || $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 !== "
" && $char !== "\r") {    //Prepend the new character    $line = $char . $line;    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f); } echo $line;

Output will be the last line of the text file will be read and displayed.

The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.

Updated on: 09-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements