Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

detect change in log file in real time php

// read.php
<?php

// Last read position
$last = 0;

// Path to the updating log file
$file = 'log.txt';

while (true) {
    // PHP caches file information in order to provide faster
    // performance; In order to read the new filesize, we need
    // to flush this cache.
    clearstatcache(false, $file);

    // Get the current size of file
    $current = filesize($file);

    // Reseted the file?
    if ($current < $last) {
        $last = $current;
    }
    // If there's new content in the file
    elseif ($current > $last) {
        // Open the file in read mode
        $fp = fopen($file, 'r');

        // Set the file position indicator to the last position
        fseek($fp, $last);

        // While not reached the end of the file
        while (! feof($fp)) {
            // Read a line and print
            print fgets($fp);
        }

        // Store the current position of the file for the next pass
        $last = ftell($fp);

        // Close the file pointer
        fclose($fp);
    }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #detect #change #log #file #real #time #php
ADD COMMENT
Topic
Name
8+8 =