I'm trying to use scandir() to list all folders in a directory into a menu structure I am making. Here is the code I have so far:
$directory = "models/";
$files = scandir($directory);
echo " <a class=\"menuitem submenuheader\" href=\"#\" >models</a>
<div class=\"submenu\">
<ul>
";
foreach($files as $file)
{
if(is_dir($file))
{
echo "<li><a href=\"$file.html\">$file</a></li>
";
}
}
echo "</ul>
</div>
";
I think I'm having an issue in the if(is_dir($file) line of the code. It is listing two items in the menu (.) and (..).
Thanks for any/all help that is offered! I very much appreciate it.
To do some testing, I replaced the foreach loop with a for loop.
$directory = "models/";
$folders = scandir($directory);
echo "<a class=\"menuitem submenuheader\" href=\"#\" >models</a>
";
echo "<div class=\"submenu\">
";
echo "<ul>
";
for ($i=0; $i<count($folders); $i++) {
if ($folders[$i] != '.' && $folders[$i] != '..') {
if(is_dir($folders[$i])) {
echo "<li><a href=\"" . $folders[$i] . ".html\">" . $folders[$i] . "</a></li>
";
}
}
}
echo "</ul>
</div>
";
Still doesn't work (Won't pull a folder within the $directory) BUT, if I change the
if(is_dir($folders[$i]))
to
if(!is_dir($folders[$i]))
it lists all the files as well as the single folder in the $directory. Not sure why it is doing this. Any ideas?
GOT IT!!!
I guess is_dir() must list the FULL PATH to the folder in question, otherwise, it doesn't work. I changed my code to this:
if(is_dir($directory . $folders[$i])) {
and it works perfect!
Thanks again for everyones help! Brainstorming with this site gets my brain juices flowing...
The comments are right. You can just add in your conditional to ignore those:
if(is_dir($file) && $file != '.' && $file != '..')
{
echo "<li><a href=\"$file.html\">$file</a></li>
";
}
Unless what you're saying is these are the ONLY results and there should be more.
Also, make sure you're calling the path correctly. You can use $_SERVER['DOCUMENT_ROOT']
and build your correct path from there. Something like this:
$directory = $_SERVER['DOCUMENT_ROOT']."/models/";