如何观看用PHP写的文件? [英] How To watch a file write in PHP?

查看:88
本文介绍了如何观看用PHP写的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make movement such as the tail command with PHP, but how may watch append to the file?

推荐答案

我不认为有某种神奇的方法可以做到这一点.您只需要连续轮询文件大小并输出任何新数据即可.这实际上是很容易的,需要注意的唯一真实的事情是文件大小和其他统计数据都存储在php中.解决方案是在输出任何数据之前调用clearstatcache().

I don't believe that there's some magical way to do it. You just have to continuously poll the file size and output any new data. This is actually quite easy, and the only real thing to watch out for is that file sizes and other stat data is cached in php. The solution to this is to call clearstatcache() before outputting any data.

这是一个快速示例,其中不包含任何错误处理:

Here's a quick sample, that doesn't include any error handling:

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

这篇关于如何观看用PHP写的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆