本文介绍了PHP:如何实时读取不断写入的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取一个不断写入的日志文件.它与应用程序位于同一服务器上.问题是文件每隔几秒钟就会被写入一次,我基本上想实时在应用程序上实时tail
该文件.
I want to read a log file that is constantly being written to. It resides on the same server as the application. The catch is the file gets written to every few seconds, and I basically want to tail
the file on the application in real-time.
这可能吗?
推荐答案
您需要循环睡眠:
$file='/home/user/youfile.txt';
$lastpos = 0;
while (true) {
usleep(300000); //0.3 s
clearstatcache(false, $file);
$len = filesize($file);
if ($len < $lastpos) {
//file deleted or reset
$lastpos = $len;
}
elseif ($len > $lastpos) {
$f = fopen($file, "rb");
if ($f === false)
die();
fseek($f, $lastpos);
while (!feof($f)) {
$buffer = fread($f, 4096);
echo $buffer;
flush();
}
$lastpos = ftell($f);
fclose($f);
}
}
(经过测试.它可以正常工作)
(tested.. it works)
这篇关于PHP:如何实时读取不断写入的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!