PHP glob() in bracketed directories

2019-03-29 05:41发布

问题:

On a Windows machine, the following script:

<?php

mkdir("c:\\[test]");
file_put_contents("c:\\[test]\\test.txt", "some content");
chdir("c:\\[test]");
echo getcwd()."\n";
var_dump(glob('*'));

?>

Displays this:

C:\[test]
array(0) {
}

When this is expected:

C:\[test]
array(1) {
    [0]=>
    string(8) "test.txt"
}

I understand that glob treats brackets as special characters, when found in the pattern parameter.

The pattern * matches any file in the current working directory. However, glob() behaves as though it was run with the pattern c:\\[test]\\*

The brackets are then being interpreted as part of the pattern, when in fact they are part of the directory.

Is glob supposed to treat the path as part of the pattern? I would rather think it should use the current directory as a starting point, and then process the pattern only.

(Attempt to summarize): The glob function acts like it's getting c:\\[test]\\* as a match pattern, and is trying to match either c:\t\*, c:\e\*, or c:\s\*. But the pattern is actually * and it shouldn't be trying to match any of that.

回答1:

This seems to be covered as an issue in this bug report on php.net: https://bugs.php.net/bug.php?id=33047

The last post on that thread is about it not being a bug, but an issue from how glob treats brackets, as part of the regular expression. I'm not sure I agree. It seems you can work around this, unless you cannot move up into the parent folder.

If you remove the first requirement of being in the inside [test] folder, you can get the file listing by using a syntax like below:

chdir('..');
$glob = glob("[[]test[]]/*");

Given these complications, I would recommend not using the glob function if you are running into issues on windows machines, and look at other file listing functions like readdir.



标签: php glob