PHP / Windows - Opendir()无法打开符号链接目录中的子目录

时间:2010-05-25 18:05:04

标签: php windows symlink

有谁知道这个问题的解决方案?我无法打开symboliclink'd目录中的子目录。我已经确认路径是正确的(甚至将路径复制并粘贴到资源管理器中,它可以很好地解析它)。这是一个奇怪的,烦人的错误:|。

示例:

  

C:\ folder \ symbolic_link \ dir1 \ dir2 - 打开dir2失败。

     

C:\ folder \ symbolic_link \ dir1 - 作品

     

C:\ folder \ real_directory \ dir1 \ dir2 - 作品

     

C:\ folder \ real_directory \ dir1 - 作品

1 个答案:

答案 0 :(得分:0)

好吧,我终于在php处理windows上的符号链接时找到了解决这个bug的黑客。使用opendir()递归迭代文件/目录时会发生错误。如果当前目录中存在目录的符号链接,则opendir()将无法读取目录符号链接中的目录。它是由php的statcache中的一些时髦引起的,可以通过在目录符号链接上调用clearstatcache()之前调用opendir()来解决(同样,必须关闭父目录的文件句柄)。

以下是修复的示例:

<?php

class Filesystem
{
    public static function files($path, $stats = FALSE)
    {
        clearstatcache();

        $ret = array();
        $handle = opendir($path);
        $files = array();

        // Store files in directory, subdirectories can't be read until current handle is closed & statcache cleared.
        while (FALSE !== ($file = readdir($handle)))
        {
            if ($file != '.' && $file != '..')
            {
                $files[] = $file;
            }
        }

        // Handle _must_ be closed before statcache is cleared, cache from open handles won't be cleared!
        closedir($handle);

        foreach ($files as $file)
        {
        clearstatcache($path);

            if (is_dir($path . '/' . $file))
            {
                $dir_files = self::files($path . '/' . $file);

                foreach ($dir_files as $dir_file)
                {
                    $ret[] = $file . '/' . $dir_file;
                }
            }
            else if (is_file($path . '/' . $file))
            {
                $ret[] = $file;
            }
        }

        return $ret;
    }
}

var_dump(filessystem::files('c:\\some_path'));

编辑:似乎必须在符号链接目录上的任何文件处理函数之前调用clearstatcache($path)。 Php没有正确缓存符号链接。