Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To watch a file write in PHP?

Tags:

php

tail

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

like image 707
freddiefujiwara Avatar asked Jul 09 '09 06:07

freddiefujiwara


People also ask

How do I view a file in PHP?

PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

How do I read the contents of a file in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

How do I echo content in PHP?

readfile("/path/to/file"); This will read the file and send it to the browser in one command. This is essentially the same as: echo file_get_contents("/path/to/file");


2 Answers

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");
like image 81
Emil H Avatar answered Oct 15 '22 10:10

Emil H


$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer\n";
    flush();
}
pclose($handle);
like image 21
Glenn Plas Avatar answered Oct 15 '22 10:10

Glenn Plas