PHP - Returning the last line in a file?

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

    The simplest naive solution is simply:

    $file = "/path/to/file";
    $data = file($file);
    $line = $data[count($data)-1];
    

    Though, this WILL load the whole file into memory. Possibly a problem (or not). A better solution is this:

    $file = escapeshellarg($file); // for the security concious (should be everyone!)
    $line = `tail -n 1 $file`;
    

提交回复
热议问题