php - 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);

?>

关于php - PHP 中的滚动日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590276/

相关文章:

javascript - register_sidebar() WordPress 与 Bootstrap 3 崩溃

php - 数学字母数字符号的正则表达式

PHP exec() 函数和 .history 文件

无论 NGINX 状态码如何,PHP-FPM 始终返回 200

php - Yii 框架从 Controller 传递变量到 View

php - 使用 htaccess 将 php 函数和一些文本添加到数百个 .htm 文件中?这行得通吗?

php - 从字符串 php 中删除文本

php - 没有框架的 OO PHP + Ajax

php - 如何向 WP_Widget_Text 添加另一个文本框

php - 如何在 PHP 中分隔数字并获取前两位数字?