问题
I need to get array of all images (or simply of all files) in directory (e.g. www.example.com/images/). I prefer to use JavaScript but it's hard to make. So should I use PHP, meybe?
Could you please help me - I'm not good at this.
Thank you very much!
回答1:
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}');
回答2:
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"]
来源:https://stackoverflow.com/questions/30622369/easiest-way-to-get-list-of-files-in-the-server-directory