首页 > 解决方案 > 使用php中文本文件的文件修改时间将文件中的数据发送到客户端

问题描述

我在 php 中使用服务器发送的事件。这是我在 php.ini 中的代码。

<?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() 返回的值也不会改变。因此文件中的数据不会发送到客户端。有什么解决方案。任何帮助表示赞赏。

标签: phpserverserver-sent-events

解决方案


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

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

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


推荐阅读