Read last line from file Read last line from file php php

Read last line from file


This should work:

$line = '';$f = fopen('data.txt', 'r');$cursor = -1;fseek($f, $cursor, SEEK_END);$char = fgetc($f);/** * Trim trailing newline chars of the file */while ($char === "\n" || $char === "\r") {    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f);}/** * Read until the start of file or first newline char */while ($char !== false && $char !== "\n" && $char !== "\r") {    /**     * Prepend the new char     */    $line = $char . $line;    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f);}fclose($f);echo $line;

Note that this solution will repeat the last character of the line unless your file ends in a newline. If your file does not end in a newline, you can change both instances of $cursor-- to --$cursor.


Use fseek. You seek to the last position and seek it backward (use ftell to tell the current position) until you find a "\n".

$fp = fopen(".....");fseek($fp, -1, SEEK_END); $pos = ftell($fp);$LastLine = "";// Loop backword util "\n" is found.while((($C = fgetc($fp)) != "\n") && ($pos > 0)) {    $LastLine = $C.$LastLine;    fseek($fp, $pos--);}fclose($fp);

NOTE: I've not tested. You may need some adjustment.

UPDATE: Thanks Syntax Error for pointing out about empty file.

:-D

UPDATE2: Fixxed another Syntax Error, missing semicolon at $LastLine = ""


You're looking for the fseek function. There are working examples of how to read the last line of a file in the comments section there.