0

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));
    }
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • you can use shell_exec https://www.php.net/manual/en/function.shell-exec.php command – Pragnesh Chauhan Apr 27 '23 at 10:41
  • Possible starter for 10 - https://stackoverflow.com/questions/1062716/php-returning-the-last-line-in-a-file – RiggsFolly Apr 27 '23 at 10:44
  • Please no shell_exec or exec... – user14706816 Apr 27 '23 at 11:20
  • hi, you may also refer this article on SO->. [What is the best way to read last lines (i.e. "tail") from a file using PHP?](https://stackoverflow.com/questions/15025875/what-is-the-best-way-to-read-last-lines-i-e-tail-from-a-file-using-php) - your question seems duplicate.. – Anant V Apr 27 '23 at 12:55
  • The first comment in the docs on this page also has an upvoted solution that might be of interest to you: https://www.php.net/manual/en/function.inotify-init.php#101093 – Chris Haas Apr 27 '23 at 18:13

0 Answers0