【问题标题】:PHP Checking Filesize to see if its changingPHP 检查文件大小以查看其是否更改
【发布时间】:2015-12-02 08:51:04
【问题描述】:

我有一个调用外部进程的网页。此过程将文本文件写入我服务器上的文件夹。我无法控制这个外部进程。

我正在尝试监视文件以查看其文件大小是否发生变化,在写入时它会发生变化。一旦外部进程停止写入,文件大小将保持不变。

我认为这样的事情可能会奏效:

<?php

$old = 0;
$new = 1;

while ($old == $new) {
    $old = filesize ('/http/test/test.txt');
    echo $old;
    sleep(2);
    $new = filesize ('/http/test/test.txt');
    echo $new;
}
echo $old;
echo $new;
echo "done";
?>

但事实并非如此。如何暂停我的脚本,直到文件停止增加大小?

这里有类似的问题,但我还没有看到不使用 flock()lsof 的例子,这两个我都无权访问。

这个可以吗?

谢谢

更新 这似乎有效。

<?php

$old = 0; $new = 1;
$filePath = "/http/test/test.txt";

while ($old != $new) {
    $old = filesize ($filePath);
    clearstatcache();
    sleep(1);
    $new = filesize ($filePath);
    clearstatcache();
}
echo "done";
?>

【问题讨论】:

  • 您的 while 循环在首次启动时永远不会像旧的一样执行!= new!
  • 谢谢。将 == 更改为 != 似乎效果更好,但 php 页面在文件完成写入之前完成。有什么想法吗?
  • set_time_limit(120);在页面顶部将允许它运行 120 秒。它通常需要执行多长时间?
  • 文档说忽略睡眠时间,所以理论上不需要设置得太高! php.net/manual/en/function.set-time-limit.php
  • 所有文件操作都被缓存,因为 PHP 不是为此类操作而设计的,并且针对短突发性能进行了优化。请参阅下面的答案,因为它可以解决您的问题。

标签: php while-loop filesize


【解决方案1】:

您需要在循环中调用 clearstatcache()。

来自http://php.net/manual/en/function.filesize.php

注意:这个函数的结果是缓存的。见 clearstatcache() 了解更多详情。

一个示例实现(这里我使用修改时间来检查更改,但您可以改用文件大小):

$filePath = '/http/test/test.txt';
$timeInSeconds = 2;

if (file_exists($filePath)) {

  $fileModificationUnixTime = filemtime($filePath);

  while (filemtime($filePath) === $fileModificationUnixTime) {
    echo 'No changes found.';
    sleep($timeInSeconds);
    clearstatcache(); // clears the cached result
  }

  echo 'Changes found';
}

【讨论】:

  • 谢谢。我已经对此进行了测试,它在文件创建完成之前返回到屏幕No changes found. Changes found。我已经使用 bash 和 yes "HelloWorld" | head -n 5000000 &gt; test.txt 测试了文件创建
  • 刚刚对我的原始帖子添加了更新。这似乎行得通。
猜你喜欢
  • 1970-01-01
  • 2012-03-16
  • 2018-09-13
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2023-03-21
相关资源
最近更新 更多