使用PHP在最后截断文件

时间:2017-12-15 17:41:20

标签: php

我有一个日志文件,我希望在PHP读取后将其截断。我的代码目前看起来像这样:

$fp = fopen($file, "r+");
ftruncate($fp, 125000);
fclose($fp);

但是,这会通过保留第一个 1Mb来截断文件。但是,我想保留文件的 last 1Mb;日志行被追加,所以我想保留最新的条目,而不是最旧的条目(post-truncate文件将始终与此代码相同)。

2 个答案:

答案 0 :(得分:0)

您不能使用ftruncate函数来执行此过程,因为它只接受最终的截断大小作为参数,并且从头开始执行截断。试一试:

// open the file for reading only
$fp = fopen($file,'r');
// place the pointer at END - 125000
fseek($fp,-125000,SEEK_END);
// read data from (END - 125000) to END
$data = fgets($fp,125000);
// close the file handle
fclose($fp);

// overwrite the file content with data
file_put_contents($file,$data);

答案 1 :(得分:0)

试试这个,很简单就行了。)

$logsToKeep = file_get_contents($file, NULL, NULL, -125000, 125000);
file_put_contents($file,$logsToKeep);

编辑:如果在v7.1之前运行版本(从php5开始的任何地方),你可以使用

$offset=filesize($file)-125000;
if($offset>0){
    $logsToKeep = file_get_contents($file, NULL, NULL, $offset, 125000);
    file_put_contents($file,$logsToKeep);
}

但这确实会降低效率。答案是效率驱动的。引用php doc,“file_get_contents()是将文件内容读入字符串的首选方法。如果操作系统支持,它将使用内存映射技术来提高性能。”因此,对负偏移的干净调用仍然是获取文件的最后N个字节的最佳方法。