Search code examples
phpfiledirectoryglob

How does glob() function work?


I know that glob() function is pretty slow but how does it work with the GLOB_ONLYDIR argument? Will it still check every file or it will use some index or whatever?


Solution

  • Looking at the source:

    /* we need to do this everytime since GLOB_ONLYDIR does not guarantee that
     * all directories will be filtered. GNU libc documentation states the
     * following: 
     * If the information about the type of the file is easily available 
     * non-directories will be rejected but no extra work will be done to 
     * determine the information for each file. I.e., the caller must still be 
     * able to filter directories out. 
     */
    if (flags & GLOB_ONLYDIR) {
        struct stat s;
    
        if (0 != VCWD_STAT(globbuf.gl_pathv[n], &s)) {
            continue;
        }
    
        if (S_IFDIR != (s.st_mode & S_IFMT)) {
            continue;
        }
    }
    

    So PHP has to check each file, regardless of whether it only asked for non-directory files.