PHP - Returning the last line in a file?

后端 未结 9 1550
鱼传尺愫
鱼传尺愫 2020-11-30 09:46

I\'m guessing it\'s fgets, but I can\'t find the specific syntax. I\'m trying to read out (in a string I\'m thinking is easier) the last line added to a log file.

9条回答
  •  囚心锁ツ
    2020-11-30 10:30

    @unique_stephen, your answer is flawed. PHP fseek returns 0 for success and -1 for failure. Storing the result in $begining (sic) and then later using it in a filter for ftell() isn't correct. If my reputation were higher I would have voted you down and left a comment. Here is a modified version of unique_stephen's function.

    function readlastline($fileName)
    {
        $fp = @fopen($fileName, "r");
        if (fseek($fp, 0) == -1)
            exit('Cannot seek to beginning of the file'); 
        $pos = -1;
        $t = " ";
        while ($t != "\n") {
            if (fseek($fp, $pos, SEEK_END) == -1)
                exit('Cannot seek to the end of the file');
            if (ftell($fp) == 0) {
                break;
            }
            $t = fgetc($fp);
            $pos = $pos - 1;
        }
        $t = fgets($fp);
        fclose($fp);
        return $t;
    }
    

    NOTE: PHP's fseek cannot manage to seek to the end of files larger than PHP_MAX_INT which is 32bit signed even on 64bit binaries.

提交回复
热议问题