PHP: List Files In A Directory By Extension.

April 10th, 2008 | by programming |

The following function lists all the files in the specified directory ( and subdirectories ), which have specified extension. If extension is not specified, it lists all files.

function listFiles ($directory,$extension = null)
{
    $results = array();
    $handler = opendir($directory);
    while ($file = readdir($handler)) {
        // check if $file isn’t this directory or its parent.
        if ($file != ‘.’ && $file != ‘..’)
            if (is_dir($directory.$file))
                $results = $this->listFiles($directory.$file,$extension);
            else
            {
                if ($extension==null)
                    $results[] = $file;
                else
                {
                    if (preg_match(“/\.”.$extension.“$/”,strtolower($file)))
                        $results[] = $file;
                }
            }
    }
    closedir($handler);
    return $results;
}

Post a Comment