gpt4 book ai didi

PHP 检查文件大小以查看其是否发生变化

转载 作者:可可西里 更新时间:2023-10-31 22:41:34 24 4
gpt4 key购买 nike

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

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

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

<?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";
?>

最佳答案

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

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

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

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

$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';
}

关于PHP 检查文件大小以查看其是否发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34038371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com