PEAR Library
PHP Code:
require_once "File/Find.php";
$files = File_Find::search("\..+$",getcwd()); // The search() method needs two parameters - the pattern to search for and the directory path to search. by using getcwd(), the application will list all the files in the directory which the PHP application is being executed from
sort($files); // sort the $files alphabetically for output
if(!empty($files)) // if $files were returned
{
echo "<ul>";
foreach($files as $file) echo "<li>" . basename(htmlspecialchars($file)) . "</li>"; // loop through each one - the basename() function returns only the file name of a path
echo "</ul>";
}
else
{
echo "<p>No files to display</p>";
}
PHP Code:
$files = scandir(getcwd(), SCANDIR_SORT_ASCENDING); // getcwd() means it will scan the current directory the PHP application is being executed from - SCANDIR_SORT_ASCENDING is a constant which tells PHP to return the files in the array in alphabetical order
echo "<ul>";
foreach($files as $file) // loop through them
{
if(($file != ".") && ($file != "..")) // the first two (or last two) returned array items will be "." and ".." - we don't want to output those
{
echo "<li>" . htmlspecialchars($file) . "</li>";
}
}
echo "</ul>";
What is the "\..+$" in the first argument of the search() method?
This is a regular expression (also referred to as regex). It essentially tells the PEAR library to match any files that start with a period character and has at least one character or more after it - so match any files, in other words - .html, .php, etc.
In regex, some characters (called metacharacters) are interpreted inside an expression. In the case above:
- \. means "match the period character literally" because the period character on its own is a metacharacter
- . means "match any character"
- + means "match the preceding one or more times" (so match a-z etc. at least once)
- $ means "end of string" - so the entire pattern must match at the end of the file name, so .php, .html, .css, .txt would all match.