Search code examples
phpjavascriptprototypejsdirectory-listing

How to list all folders on a server with PHP and JavaScript


On my webserver i have several directories with files in them like:

  • afolder/file.xml
  • anotherfolder/file.xml
  • stillanother/file.xml

The files contain information about some locations I want to show on a Map (with openlayers) so I need the files in JS. The problem is that i don't know what the folders are called and how many of them are there , so I need a list of them.

I need something like this:

for each (folder as f)
    map.showLocations(f/file.xml)

How could this be done ?

I searched for the solution but all i found was about files and folders on client side. I am using prototype js and it is possible to use PHP.


Solution

  • If you list your directories in a PHP variable $directories, you can echo to the page something like

    echo '<script>var Directories = '.json_encode($directories).';</script>';
    

    now you have inside your page a javascript variables which you can iterate over and do your magic

    for (dir in Directories) {
      map.showLocations(Directories[dir]/file.xml);
    }
    

    Another option is to have an AJAX request to do it for you (I am using jQuery for this example because I don't know prototype bu it should be roughly the same)

    $.getJSON('directories.php', function(data) {
      $.each(data, function(index, value) {
        map.showLocations(value+'/file.xml');
      });
    });
    

    and your PHP code should be something like this

    <?php
      *** iterate over the directories and save them into an array ***
      echo json_encode($directories);
      exit();
    ?>