Please try this code. I have tested it it works fine. I use \r\n
for line break so that your text file is more readable.
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
now you check if the number of lines in the file exceed your limit, then remove the old lines from the top the the file and enter new line on the top, else just enter new line.
$block = 5; //block consist of 5 lines
$remove_blocks = 10; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 20;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
Edit: put this code in a new test.php adn experiment with it
<?php
$block = 2; //block consist of 5 lines
$remove_blocks = 1; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 5;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$array = array_slice($array, -1);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
?>