Check that the path is a directory, handle a failed scandir() call, remove the . and .. entries, and escape file names before displaying them in HTML.
<?php
$directory = __DIR__ . '/test_dir';
if (!is_dir($directory)) {
throw new RuntimeException('Directory not found.');
}
$entries = scandir($directory, SCANDIR_SORT_ASCENDING);
if ($entries === false) {
throw new RuntimeException('Unable to read directory.');
}
foreach (array_diff($entries, ['.', '..']) as $entry) {
echo htmlspecialchars($entry, ENT_QUOTES, 'UTF-8') . '
';
}
?>
$ar=scandir('test_dir'); // Change this path
print_r($ar);
or
$ar=scandir('C:\\dir_name\\abc\\'); // Change this path to directory
foreach ($ar as $key => $val) {
echo "$key -> $val <br>";
}

Scandir('directory_sting',sort_order,'context');
Directy_sting: Sort_order: (Optional)Context:$ar=scandir('.');
print_r($ar);
Listing all files and directory of up folder
$ar=scandir('..');
print_r($ar);
We can develop a small script which will first list file and directory of current directory. All listed directory will have hyperlink to list files and directory present inside that on click. We have used is_dir function to check if the output string is a directory or not.
$var=$_GET['var'];
if(strlen($var)==0){
$var='.';
}
$ar=scandir($var);
while (list ($key, $val) = each ($ar)) {
if(is_dir($val)){ // True if directory
echo "<a href=scandir.php?var=$val>$val</a><br>";
}else {
echo "$val<br>";
}
}
<?php
@$var=$_GET['var'];
$path = '';
if(strlen($var)==0){
$path='';
}else{
$path=$var;
}
$cwd=getcwd();
$cwd=$cwd.$path;
chdir($cwd);
echo "<br>Current Working Directory : ".getcwd()."<br>";
$ar=scandir($cwd);
while (list ($key, $val) = each ($ar)) {
$path2=$path."".$val;
if(is_dir($val)){
echo "<a href=dir-listing.php?var=$path2>$val</a><br>";
}else {
echo "$val<br>";
}
}
?>
<?php
@$var=$_GET['var'];
$path = '';
if(strlen($var)==0){
$path='';
}else{
$path=$var;
}
$cwd=getcwd();
$cwd=$cwd.$path;
chdir($cwd);
echo "<br>Current Working Directory : ".getcwd()."<br>";
$ar=scandir($cwd);
while (list ($key, $val) = each ($ar)) {
$path2=$path."".$val;
if(is_dir($val)){
echo "<a href=dir-listing.php?var=$path2>$val</a><br>";
}else {
if($val<>'dir-listing.php'){
// Uncommenting below line will delete your files of each folder you list ////
//unlink($val); // This will delete your files !!!!
}
echo "$val<br>";
}
}
?>
Script to list all file extension types with total numbers by using Scandir and array functions
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.