Skip to main content

PHP function to find files by extension (recursively).

<?php

if (!function_exists('get_file_list_by_ext')) {
    /**
     * Get files by extension.
     *
     * Read the specified directory and build an array containing the files.
     * Any sub-folders contained within the specified path are also read.
     *
     * @param string $sourceDir   Path to the directory.
     * @param array  $extensions  Extensions of files to retrieve.
     * @param bool   $includePath Whether the path should be included with the file name.
     * @param bool   $recursive   Whether directories will be searched recursively.
     *
     * @return array An array of file.
     */
    function get_file_list_by_ext($sourceDir, $extensions = array(), $includePath = false, $recursive = false)
    {
        static $files = array();

        if ($fp = @opendir($sourceDir)) {
            // Reset the array and ensure $sourceDir has a trailing slash on the initial call
            if (false === $recursive) {
                $files = array();
                $sourceDir = sprintf("%s%s", rtrim(realpath($sourceDir), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR);
            }

            while (false !== ($file = readdir($fp))) {
                if (0 === strncmp($file, '.', 1)) {
                    continue;
                }
                if (@is_dir("{$sourceDir}{$file}")) {
                    get_file_list_by_ext(sprintf("{$sourceDir}{$file}%s", DIRECTORY_SEPARATOR), $extensions, $includePath, true);
                } elseif (in_array(pathinfo($file, PATHINFO_EXTENSION), $extensions)) {
                    $files[] = $includePath ? "{$sourceDir}{$file}" : $file;
                }
            }

            return $files;
        }

        return array();
    }
}