I need to write a PHP script which reads lines of a log file (which is frequently appending new lines) and I expect the script to:
- When running the script, it should only read new appended lines and not the already existing lines in the file (like "tail -n0 -f" would do in bash)
- If log file is rotated or cleaned, the script should continue to read the file (like "tail -F" would do in bash)
I managed to do it easily in bash with the following code:
tail -n0 -F "$STATS_LOG_PATH" | \
while read LINE; do
    # echoing the line or do whatever
    echo "$LINE"
done
But now I really need to do the same in PHP. Here is my attempt but it is far from what I want:
// Open log file
$fh = fopen('/tmp/test.log', 'r');
while (true) {
    // Read line
    $line = fgets($fh);
    
    // Print line if any or sleep
    if ($line !== false) {
        echo $line . PHP_EOL;
    } else {
        // sleep for 0.1 seconds
        usleep(0.1 * 1000000);
        fseek($fh, ftell($fh));
    }
}
 
    