使用 php 中文本文件的文件修改时间将文件中的数据发送到客户端

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

我在 php 中使用服务器发送的事件。这是我在 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);
}

即使文件被修改,filemtime() 返回的值也不会改变。因此文件中的数据不会发送到客户端。这是什么解决方案。感谢任何帮助。

如评论中所述,只需像这样添加clearstatcache:

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

来自 PHP 文档:
注意:此函数的结果 (filemtime) 被缓存。有关详细信息,请参阅 clearstatcache()。