scandir() is convenient for a simple listing. Skip the dot entries, escape output sent to HTML, and do not expose private server paths to visitors.
$dir = __DIR__ . '/docs';
foreach (scandir($dir) as $name) {
if ($name === '.' || $name === '..') {
continue;
}
echo htmlspecialchars($name) . '<br>';
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
$handle=opendir("."); // open the current directory
$handle=opendir("E:\\my_dir\\"); // OR use the path
while (($file = readdir($handle))!==false) {
echo "$file <br>";
}
closedir($handle);
Many times we have to display the list of files in a directory. We can keep the script in any location and by using the file path we can display the files inside the directory. opendir():readdir():closedir():$path='images/';// change the path here related to this page
$handle=opendir($path);
while (($file = readdir($handle))!==false) {
if(strlen($file)>3){echo "<img src=$path$file> <br>";}
}
closedir($handle);
You can also list the files and directories by using dir function scandir() function listDirectory($dir) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$path = $dir . '/' . $file;
if (is_dir($path)) {
listDirectory($path);
} else {
echo $path . "
";
}
}
}
}
listDirectory('E:\\dir-name\\sub-dir');
$dir = 'your-directory';
$files = scandir($dir);
usort($files, function($a, $b) use ($dir) {
return filemtime("$dir/$b") - filemtime("$dir/$a");
});
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo "$file - " . date("F d Y H:i:s", filemtime("$dir/$file")) . "<br>";
}
}
$dir = 'your-directory';
$files = scandir($dir);
foreach ($files as $file) {
if (preg_match('/\.txt$/', $file)) {
echo $file . "<br>";
}
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
06-07-2021 | |
| Superb | |