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>";
}
?>