有没有办法在windows和linux上使用php检测文件夹中的变化?

我正在寻找一种使用 php 检测文件夹更改的解决方案.该应用程序可以在两个平台(linux 和 windows)上运行.只要结果相同,我可能会为每个平台使用不同的方法.我想要的是:

I'm looking for a solution to detect changes in folder(s) using php. The application may run on both platforms(linux and windows). I may use different methods for each platform as long as results are the same. What I desire is :

  1. 如果将文件/文件夹添加到目录中,我希望我的应用检测到这个新文件并读取其属性(size,filetime 等)
  2. 如果保存了现有文件/文件夹/更改/删除了内容,我需要检测此文件是否已更改
  3. 如果我可以监视 apache 的 webroot 之外的基本文件夹(例如 c: mpd:music 在 windows 上或 /home/ertunc 在 linux 上)
  1. If a file/folder is added to a directory, I want my app to detect this new file and read its attributes (size,filetime etc)
  2. If a existing file/folder is saved/contents changed/deleted, I need to detect this file is changed
  3. It would be better if I can monitor a base folder outside webroot of apache (such as c: mp, or d:music on windows or /home/ertunc on linux)

我在 inotify 上阅读了一些内容,但我不确定它是否满足我的需求.

I read something on inotify but I'm not sure it meets my needs.

推荐答案

因此,如果您正在与上次检查相比进行检查,而不仅仅是在更改后立即更新,您可以执行以下操作.

So if you are checking compared to the last time you checked rather than just being updated as soon as it changes you could do the following.

您可以创建一个目录的 MD5,存储此 MD5,然后将新的 MD5 与旧的进行比较,看看情况是否发生了变化.

You could create an MD5 of a directory, storew this MD5 then compare the new MD5 with the old to see if things have changed.

下面的函数取自 http://php.net/manual/en/function.md5-file.php 会为你做这件事.

The function below taken from http://php.net/manual/en/function.md5-file.php would do this for you.

function MD5_DIR($dir)
{
    if (!is_dir($dir))
    {
        return false;
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read()))
    {
        if ($entry != '.' && $entry != '..')
        {
             if (is_dir($dir.'/'.$entry))
             {
                 $filemd5s[] = MD5_DIR($dir.'/'.$entry);
             }
             else
             {
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}

尽管如此,这相当低效,因为您可能知道,如果第一位不同,则检查目录的全部内容是没有意义的.

This is rather inefficient though, since as you probably know, there is no point checking the entire contents of a directory if the first bit is different.

相关文章