I have a huge log file ( around 1,000,000 lines ). I would like to obtain the last line and remove it from the file using PHP. What is the quickest way to do so?
I tried:
$logfile = escapeshellarg("/path/to/logfile");
$lastline = `tail -n 1 "$logfile"`; // obtained the last line
Is the above approach efficient enough? and how to remove the last line from the file?
From Jon's answer below, here are the codes :
$buffer_size = 1000;
$fh = fopen("/path/to/logfile", "r+");
fseek($fh, -$buffer_size, SEEK_END);
$content = fgets($fh, 100);
while(strrpos($content, PHP_EOL) != false) {
fseek($fh, -$buffer_size); // move backward for extra -1000
$content = fgets($fh, $buffer_size);
}
$pos_last_eol = strrpos($content, PHP_EOL);
fseek($fh, $pos_last_eol); // seek to that position
ftruncate($fh, ftell($fh));
fclose($fh);