PHP 删除文件的第一行直到达到阈值

PHP delete first row of file till threshold is reached

我想 trim 我的日志文件到 7KB。 但是 trim 只 运行 一次,文件大小也不会更新。

代码如下:

$thresholdKB = "7";
$files = glob('logs/*.{log}', GLOB_BRACE);

foreach($files as $file) {
    $filesizeKB = filesize("$file") / 1024;
    if ($filesizeKB > $thresholdKB){
        while ($filesizeKB > $thresholdKB) {
            $filesizeKB = filesize("$file") / 1024;

            $lines = file("$file"); 
            unset($lines[0]); 
            $fp = fopen("$file", 'w'); 
            fwrite($fp, implode('', $lines)); 
            fclose($fp);
        }
    }
}

filesize 的结果被缓存。更新文件后需要调用clearstatcache()

https://www.php.net/manual/en/function.clearstatcache.php