Easiest way to get list of files in the server directory

杀马特。学长 韩版系。学妹 提交于 2019-12-04 03:24:24

Javascript cannot fetch all files on a server, as it is a client-side langugage.

http://php.net/manual/en/function.glob.php is what you need.

$all = glob('/path/to/dir/*.*');

$images = glob('/path/to/dir/*.{jpg,png,gif}');

I disagree with @mariobgr. If there is no server setting preventing a directory listing, then the html generated by requesting that directory can be parsed for the contents.

$ tree maindir
maindir
├── index.html
└── somedir
    ├── doc1
    ├── doc2
    └── doc3

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"><!--  JQUERY  -->

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  </script>
  <title></title>
</head>
<body>
  <h1>Listing /somedir</h1><!-- Custom Script (defered load, after dom ready) -->
  <script>
    $.get('http://localhost/maindir/somedir', (data) => 
    {
        console.log(data);
        let listing = parseDirectoryListing(data);
        $('body').append(JSON.stringify(listing));
    });

    function parseDirectoryListing(text) 
    {
        let docs = text
                     .match(/href="([\w]+)/g) // pull out the hrefs
                     .map((x) => x.replace('href="', '')); // clean up
        console.log(docs);
        return docs;
    }   
  </script>
</body>

Visiting localhost/maindir produces:

Listing /somedir
["doc1","doc2","doc3"]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!