Osa Osa - 1 year ago 110
PHP Question

PHP file write - max lines

How to put a limit for writing in a file, if it hit the limit then remove the last line..

As example here's a file:

Line 3
Line 2
Line 1

i want to max line it for 3 lines only.. so when i write a new line using any append functions it removes the last line.. Let's say i just wrote a new line ( Line 4 ).. so it goes to the last one and remove it, result should be :

Line 4
Line 3
Line 2

And for a new written line (Line 5):

Line 5
Line 4
Line 3

numeric lines is not required, i just want to remove the last line if there's a new added line via an append functions (file_put_contents / fwrite) and max it by 3 or a specific number i give

Answer Source

You can try

$max = 3;
$file = "log.txt";
addNew($file, "New Line at : " . time());

Function Used

function addNew($fileName, $line, $max = 3) {
    // Remove Empty Spaces
    $file = array_filter(array_map("trim", file($fileName)));

    // Make Sure you always have maximum number of lines
    $file = array_slice($file, 0, $max);

    // Remove any extra line 
    count($file) >= $max and array_shift($file);

    // Add new Line
    array_push($file, $line);

    // Save Result
    file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));