3

How can I make my code only display links to the folders and not the files in the directory?

$d = dir(".");
echo "<ul>";
while(false !== ($entry = $d->read())) {
    echo "<li><a href='{$entry}'>{$entry}</a></li>";
}
echo "</ul>";
$d->close();
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71

3 Answers3

8
$d = dir(".");

echo "<ul>";

while (false !== ($entry = $d->read()))
{
    if (is_dir($entry) && ($entry != '.') && ($entry != '..'))
        echo "<li><a href='{$entry}'>{$entry}</a></li>";
}

echo "</ul>";

$d->close();
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
2

You should just be able to wrap your current code with a call to is_dir:

while(false !== ($entry = $d->read())) {
    if (is_dir($entry)) {
        echo "<li><a href='{$entry}'>{$entry}</a></li>";
    }
}

If you want to remove the "dot" directories (. and ..), use the following:

if (is_dir($entry) && !in_array($entry, ['.', '..'])) {
...
iainn
  • 16,826
  • 9
  • 33
  • 40
  • Thanks, that worked like a charm! The only problem i got with this solution is that i get these dots beneath the folders, what's that about? –  Dec 27 '17 at 21:31
  • @Unknown The dots are another "directory", really it's the parent directory of whatever directory you are in. – GrumpyCrouton Dec 27 '17 at 21:33
  • I see! Is there a way to remove it from the code, or do i have to use css to remove it? –  Dec 27 '17 at 21:34
  • Btw, i LOVE this platform. So freaking fast answers, it's pure magic! –  Dec 27 '17 at 21:35
  • I've added a way to remove the dots – iainn Dec 27 '17 at 21:36
0

Just check if the $entry is a directory:

$d = dir(".");
echo "<ul>";
while(false !== ($entry = $d->read())) {
if(is_dir($entry))
    echo "<li><a href='{$entry}'>{$entry}</a></li>";
}
echo "</ul>";
$d->close();
RDev
  • 1,221
  • 1
  • 12
  • 17