You can use opendir
and readdir
. Here's a breakdown:
We use __DIR__
to make the path relative to the directory of the current script, just to be safe:
$dir = __DIR__ . '/sebis_files';
Next we open the directory to read it's entries.
We call readdir
, which will return a 'resource' object, or false if $dir
is not a readable directory:
if ($dh = opendir($dir))
{
The directory is successfully opened.
We now call readdir
on that directory. We use the return value of opendir, the mysterious 'resource' object, that will let PHP know what directory we are reading.
Every time we call readdir
it will give us the next entry in the directory. When there are no more entries, readdir
will return false:
while ( ($entry = readdir($dh)) !== false)
{
We have read a directory $entry
: the name of a file or sub-directory inside $dir
. So, it's not a full pathname. Let's print it's name, along with whether it is a directory or a file. We will use is_file
and is_dir
, but we will need to pass the full pathname (hence "$dir/$entry"):
if ( is_dir( "$dir/$entry" ) )
echo "Directory: $entry<br/>";
else if ( is_file( "$dir/entry" ) )
echo "File: $entry<br/>";
}
we are done with the directory, let's close it to free the resource:
closedir($dh);
}
But what if $dir
cannot be opened for reading? Let's print a warning:
else
echo "<div class='warning'>cannot open directory!</div>";