Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

php - Get the files inside a directory

How to get the file names inside a directory using PHP?

I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a lot of ways. The older way is scandir but DirectoryIterator is probably the best way.

There's also readdir (to be used with opendir) and glob.

Here are some examples on how to use each one to print all the files in the current directory:

DirectoryIterator usage: (recommended)

foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '<br>';
}

scandir usage:

$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

opendir and readdir usage:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    closedir($handle);
}

glob usage:

foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

As mentioned in the comments, glob is nice because the asterisk I used there can actually be used to do matches on the files, so glob('*.txt') would get you all the text files in the folder and glob('image_*') would get you all files that start with image_


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...