Search code examples
phpglob

why php's glob behaves differently (returning files when not supposed to)?


I was trying to add globstar to php, but suddenly I stumbled on this weird behavior:

$ php --version
PHP 5.4.15-1~dotdeb.1 (cli) (built: May 11 2013 19:59:55)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
$ ls -p
1/  f1

$ echo *
1 f1
$ php -r 'print_r(glob("*"));'
Array
(
    [0] => 1
    [1] => f1
)

$ echo */
1/
$ php -r 'print_r(glob("*/"));'
Array
(
    [0] => 1/
)

$ echo ./*/
./1/
$ php -r 'print_r(glob("./*/"));'
Array
(
    [0] => ./1/
    [1] => ./f1
)

Is this a bug?


Solution

  • yaccz was right. As I can see, php's implementation entrusts libc's glob with doing all the dirty work. Also,

    $ cat 1.c
    
    #include <glob.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        glob_t globbuf;
        int i;
    
        glob(argv[1], 0, NULL, &globbuf);
        for (i = 0; i < globbuf.gl_pathc; i++)
            printf("%s\n", globbuf.gl_pathv[i]);
        globfree(&globbuf);
        return 0;
    }
    $ gcc 1.c -o 1.c.out
    
    $ ldd 1.c.out | grep libc
            libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5f2222d000)
    $ dpkg -S /lib/x86_64-linux-gnu/libc.so.6
    libc6: /lib/x86_64-linux-gnu/libc.so.6
    $ dpkg -l | grep -E 'libc6[^-]'
    ii  libc6                               2.13-38                      Embedded GNU C Library: Shared libraries
    
    $ ./1.c.out '*'
    1
    f1
    
    $ ./1.c.out '*/'
    1/
    
    $ ./1.c.out './*/'
    ./1/
    ./f1