How To watch a file write in PHP?

荒凉一梦 提交于 2019-11-26 20:27:54

问题


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


回答1:


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



回答2:


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



回答3:


Checkout php-tail on Google code. It's a 2 file implementation with PHP and Javascript and it has very little overhead in my testing.

It even supports filtering with a grep keyword (useful for ffmpeg which spits out frame rate etc every second).




回答4:


$handler = fopen('somefile.txt', 'r');

// move you at the end of file
fseek($handler, filesize( ));
// move you at the begining of file
fseek($handler, 0);

And probably you will want to consider a use of stream_get_line




回答5:


Instead of polling filesize you regular checking the file modification time: filemtime




回答6:


Below is what I adapted from above. Call it periodically with an ajax call and append to your 'holder' (textarea)... Hope this helps... thank you to all of you who contribute to stackoverflow and other such forums!

/* Used by the programming module to output debug.txt */
session_start();
$_SESSION['tailSize'] = filesize("./debugLog.txt");
if($_SESSION['tailPrevSize'] == '' || $_SESSION['tailPrevSize'] > $_SESSION['tailSize'])
{
      $_SESSION['tailPrevSize'] = $_SESSION['tailSize'];
}
$tailDiff = $_SESSION['tailSize'] - $_SESSION['tailPrevSize'];
$_SESSION['tailPrevSize'] = $_SESSION['tailSize'];

/* Include your own security checks (valid user, etc) if required here */

if(!$valid_user) {
   echo "Invalid system mode for this page.";
}
$handle = popen("tail -c ".$tailDiff." ./debugLog.txt 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer";
    flush(); 
}
pclose($handle);


来源:https://stackoverflow.com/questions/1102229/how-to-watch-a-file-write-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!