我想用 PHP 编写/读取滚动日志文件,其中仅存储/读取最新的 ~300 行,而丢弃任何旧的。我不确定最有效的方法 - 它需要快速工作,因为它在高流量网站上记录页面点击率。
另一个 PHP 脚本将定期读取日志文件并使用数据进行计算。 PHP 文件函数太多,我不知道从哪里开始!
我认为我的托管环境无法访问诸如 tail
或 awk
或类似命令,因此首选纯 PHP 解决方案。任何帮助表示赞赏!
最佳答案
您可以使用 fopen: http://us3.php.net/manual/en/function.fopen.php
$mode = 'a+'; // opens the file with read/write access and sets the pointer to the end of the file
$handle = fopen ($filename, $mode);
接下来,您将文件抽取到一个数组中,并删除除最后 300 行之外的所有内容。
如果您真的只想将文件保持在一定大小(您说的是 ~300 行),那么您可以使用 fseek http://us3.php.net/manual/en/function.fseek.php (来自手册):
<?php
$fp = fopen('somefile.txt', 'r');
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);
?>
关于php - PHP 中的滚动日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590276/