php - PHP 中的滚动日志文件

我想用 PHP 编写/读取滚动日志文件,其中仅存储/读取最新的 ~300 行,而丢弃任何旧的。我不确定最有效的方法 - 它需要快速工作,因为它在高流量网站上记录页面点击率。

另一个 PHP 脚本将定期读取日志文件并使用数据进行计算。 PHP 文件函数太多,我不知道从哪里开始!

我认为我的托管环境无法访问诸如 tailawk 或类似命令,因此首选纯 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);

?>

https://stackoverflow.com/questions/7590276/

相关文章:

xml - 如何使用受控词汇表或分类法来定义 XML 元素名称或属性名称?

debugging - Valgrind 在 Fortran 代码中显示未初始化的变量

ruby-on-rails - rails 不见了

interface-builder - 如何将 "turn off"透明度从 UIView 继承到

pdf - 打印时将空白页插入 PDF

visual-studio - 更改远程桌面键盘快捷方式

sql-server - sql server 中的语言环境感知排序

asp.net - 提交按钮间歇性地在 Chrome 中不执行任何操作

asp.net - asp.net 中的用户控件 (ascx) 及其可绑定(bind)属性未显示在数

.net - 如何获取 ASMX 生成的 WSDL soap :address to use htt