如何观看PHP中的文件写入?
我想用PHP进行诸如tail命令之类的移动,但是如何监视附加到文件?
我不相信有一些神奇的方法可以做到这一点。您只需要不断轮询文件大小并输出任何新数据即可。这实际上很容易,唯一需要注意的是文件大小和其他统计数据缓存在php中。此问题的解决方案是在输出任何数据之前进行调用。clearstatcache()
下面是一个快速示例,其中不包含任何错误处理:
function follow($file)
{
$size = 0;
while (true) {
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}
$fh = fopen($file, "r");
fseek($fh, $size);
while ($d = fgets($fh)) {
echo $d;
}
fclose($fh);
$size = $currentSize;
}
}
follow("file.txt");
$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer\n";
flush();
}
pclose($handle);