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);
The fastest way to obtain and remove the last line from a big file is:
strrposuntil you find an end-of-line marker¹ftruncateto cut off the part of the file beginning with the end of line foundThis is what any program would have to do. If you decide to “cheat” by offloading the first seven steps to an external utility like
tailyou can remove the line from the file with one call toftruncate, but: be careful when calculating the offset at which to truncate if you do not wish to leave trailing end-of-line character(s) in the file.