Using file modified time of a text file in php to send data in the file to client side

Viewed 30

Im using server sent events in php. Here is my code in php.

<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
$lastMod = 0;
$filename = "tmp.txt";
$filetext = '';
while (true) {
    $time = filemtime("tmp.txt");
    if($time != $lastMod){
        $lastMod = $time;
        $file = fopen($filename, "r");

        if ($file == false) {
            echo ("Error in opening file");
            exit();
        }
        
        $counter = $counter +1;
        $filesize = filesize($filename);
        $filetext = fread($file, $filesize);
        fclose($file);
        
        echo 'data: This is a message at time '. $filetext . $time. "\n\n";
    
    }
    ob_end_flush();
    flush();
    if (connection_aborted()) break;
    sleep(2);
}

Even if the file was modified the value returned by the filemtime() doesn't change. So data in the file doesn't go to the client. What is the solution for this. Any help is appreciated.

1 Answers

As stated in comments, just add clearstatcache like this:

clearstatcache();
$time = filemtime("tmp.txt");

From PHP documentation:
Note: The results of this function (filemtime) are cached. See clearstatcache() for more details.

Related