Search code examples
phplogginglines

How to keep last n number of line from log file in php


I want to delete all lines from old log files and keep fresh 50 lines which is at the bottom.

How can I do something like this and if possible can we change the orientation of these lines,

normal input

111111
2222222
3333333
44444444
5555555

output like

555555
4444444
3333333
22222
111111

To see the fresh log at top and 50 or 100 lines only.

How to join it with this one?

// set source file name and path 
$source = "toi200686.txt"; 
// read raw text as array 
$raw = file($source) or die("Cannot read file"); 
// join remaining data into string 
$data = join('', $raw); 
// replace special characters with HTML entities 
// replace line breaks with <br />  
$html = nl2br(htmlspecialchars($data)); 

It made the output as an HTML file. So how will your code run with this?


Solution

  • $lines = file('/path/to/file.log'); // reads the file into an array by line
    $flipped = array_reverse($lines); // reverse the order of the array
    $keep = array_slice($flipped,0, 50); // keep the first 50 elements of the array
    

    from there you can dow whatever with $keep. for example if you want to spit it back out:

    echo implode("\n", $keep);
    

    or

    file_put_contents('/path/to/file.log', implode("\n", $keep));