php - 使用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() 返回的值也不会改变。因此文件中的数据不会发送到客户端。有什么解决方案。任何帮助表示赞赏。
解决方案
如评论中所述,只需像这样添加 clearstatcache :
clearstatcache();
$time = filemtime("tmp.txt");
来自 PHP 文档:
注意:此函数 (filemtime) 的结果被缓存。有关详细信息,请参阅clearstatcache ()。
推荐阅读
- r - 使用 caret::varImp 时如何修复错误?
- f# - 您如何使用通用转换器将 FileHelpers.engine 与 F# 选项类型一起使用?
- html - 选择单选按钮后刷新 Angular-Component
- xml - 使用自定义求解器 xml 配置时,无法在 optaplanner 中自动装配 ScoreManager
- c# - C#(或任何其他代码,因为唯一需要的是逻辑) - 永久禁用先前条件的条件
- javascript - 如何在 React 中包含自定义 Javascript 文件
- node.js - 使用后端快速应用程序设置 AWS ELB
- java - BabelNet 中的域限制
- python - 如何在 Toplevel 上存储数据?
- javascript - 用户滚动后更改标题背景