How can a PHP script be written to only display the 20 most recent log entries and delete the oldest ones?
To achieve this, we can use a combination of reading the log file, storing the entries in an array, keeping track of the number of entries, displaying only the 20 most recent ones, and deleting the oldest entries if the total number exceeds 20.
<?php
$logFile = 'logfile.txt';
$maxEntries = 20;
// Read log file and store entries in an array
$entries = file($logFile, FILE_IGNORE_NEW_LINES);
// Display only the 20 most recent entries
$recentEntries = array_slice($entries, -$maxEntries);
// Delete oldest entries if total number exceeds 20
if (count($entries) > $maxEntries) {
$entries = array_slice($entries, -$maxEntries);
file_put_contents($logFile, implode(PHP_EOL, $entries));
}
// Display the recent entries
foreach ($recentEntries as $entry) {
echo $entry . "<br>";
}
?>
Keywords
Related Questions
- What are the potential pitfalls to avoid when using Axios to send data to a database and update values in a PHP project like Scrum Poker / Planning Poker?
- How can one efficiently convert a formatted string stored in a database into an array for further processing in PHP?
- How can PHP code be structured to collect and return a collection of IDs from a database query?