PHP - Returning the last line in a file?

后端 未结 9 1551
鱼传尺愫
鱼传尺愫 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:52

    This looks like it is what you are looking for:

    tekkie.flashbit.net: Tail functionality in PHP

    It implements a function that uses fseek() with a negative index to roll up the file from the end. You can define how many lines you want to be returned.

    The code also is available as a Gist on GitHub:

    // full path to text file
    define("TEXT_FILE", "/home/www/default-error.log");
    // number of lines to read from the end of file
    define("LINES_COUNT", 10);
    
    
    function read_file($file, $lines) {
        //global $fsize;
        $handle = fopen($file, "r");
        $linecounter = $lines;
        $pos = -2;
        $beginning = false;
        $text = array();
        while ($linecounter > 0) {
            $t = " ";
            while ($t != "\n") {
                if(fseek($handle, $pos, SEEK_END) == -1) {
                    $beginning = true; 
                    break; 
                }
                $t = fgetc($handle);
                $pos --;
            }
            $linecounter --;
            if ($beginning) {
                rewind($handle);
            }
            $text[$lines-$linecounter-1] = fgets($handle);
            if ($beginning) break;
        }
        fclose ($handle);
        return array_reverse($text);
    }
    
    $fsize = round(filesize(TEXT_FILE)/1024/1024,2);
    
    echo "".TEXT_FILE."\n\n";
    echo "File size is {$fsize} megabytes\n\n";
    echo "Last ".LINES_COUNT." lines of the file:\n\n";
    
    $lines = read_file(TEXT_FILE, LINES_COUNT);
    foreach ($lines as $line) {
        echo $line;
    }
    

提交回复
热议问题