如何用PHP编写文件?

fre*_*ara 16 php tail

我想用PHP进行诸如tail命令之类的移动,但是如何观看附加到文件?

Emi*_*l H 24

我不相信有一些神奇的方法可以做到这一点.您只需连续轮询文件大小并输出任何新数据.这实际上非常简单,唯一需要注意的是文件大小和其他统计数据缓存在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");
Run Code Online (Sandbox Code Playgroud)


Gle*_*las 11

$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer\n";
    flush();
}
pclose($handle);
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 5

在Google代码上查看php-tail.这是一个使用PHP和Javascript的2文件实现,它在测试中的开销很小.

它甚至支持使用grep关键字进行过滤(对于每秒吐出帧速率等的ffmpeg非常有用).