I decided to teach php and when writing a simple file manager with the ability to go deep into folders I ran into a problem. After logging into the child folder, does not execute is_dir in a loop. those. folders which are inside do not turn around the link. while in the root, in the directory where the file being processed is located - everything is ok. Tell me where I was mistaken or what did I miss?

$dir = isset($_GET['link']) ? scandir($_GET['link']) : scandir('.'); if(isset($dir)) { foreach($dir as $i) { if($i != '.' && $i != '..') if(is_dir($i)) { echo '<p><strong><a href="/program.php?link='.(isset($_GET['link']) ? $_GET['link'].'/'.$i : $i).'">[ '.$i.' ]</a></strong></p>'; } else { echo '<p>'.$i.'</p>'; } } } 

1 answer 1

is_dir checks the name of the folder under consideration. but looking for it relative to the current. and the current one seems to be the one from where you launch this very search. and there is no such folder. just add in the loop at the beginning of the file name path to the current folder. the path will be absolute and is_dir will be able to understand that this is a real folder.

Sample code based on what was in question. Two patches were fixed - a variable was added at the very beginning, and it is also used inside if'a.

 $currentDir = __DIR__ . '/' . (isset($_GET['link']) ? $_GET['link'] . '/' : ''); $dir = scandir($currentDir); if (isset($dir)) { foreach ($dir as $i) { if ($i != '.' && $i != '..') { if (is_dir($currentDir . $i)) { echo '<p><strong><a href="?link=' . (isset($_GET['link']) ? $_GET['link'] . '/' . $i : $i) . '">[ ' . $i . ' ]</a></strong></p>'; } else { echo '<p>' . $i . '</p>'; } } } } 

You can run the code in the console like this:

 $ php -S 127.0.0.1:8008 /путь/до/этого/файла.php 

And then open in the browser http://127.0.0.1:8008/

  • Moreover, if you manually set the path to the internal folder - it works, but it doesn’t wrap the link ... - cooledit
  • In your case there is a hard binding to the path: '/my/root/dir' . I use scandir('.') , Which is more universal and will suit any folder where to mark a file. - cooledit
  • In my case, this is a prototype. In your rootDir, it will be __DIR__ and there are no problems. - Lexx918
  • if you set __DIR__ you will not be able to go deep into the internal folders, since __DIR__ will remain unchanged with respect to the file being processed. - cooledit
  • it should not change. __DIR__ + selected_directory + available_for_to __DIR__ . - Lexx918