What are the best practices for reading the last line of a file in PHP without iterating through all lines?

When reading the last line of a file in PHP without iterating through all lines, one efficient approach is to use fseek() to move the file pointer to the end of the file, then backtrack to find the beginning of the last line. This method avoids reading unnecessary lines and is particularly useful for large files.

$filename = 'example.txt';

$file = fopen($filename, 'r');
fseek($file, -2, SEEK_END); // Move the pointer to the second last byte of the file

while (($char = fgetc($file)) !== false && $char !== "\n") {
    fseek($file, -2, SEEK_CUR); // Move the pointer back by 2 bytes
}

$lastLine = trim(fgets($file)); // Read the last line and trim any whitespace

fclose($file);

echo $lastLine;