获取目录中的文件 [英] Get the Files inside a directory
问题描述
如何使用PHP获取目录中的文件名?
How to get the file names inside a directory using PHP?
我找不到使用Google的相关命令,所以希望这个问题能对那些类似的问题有所帮助.
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.
推荐答案
有很多方法.较旧的方法是 scandir
,但
There's a lot of ways. The older way is scandir
but DirectoryIterator
is probably the best way.
以下是一些示例,说明如何使用每个示例打印当前目录中的所有文件:
Here are some examples on how to use each one to print all the files in the current directory:
foreach (new DirectoryIterator('.') as $file) {
if($file->isDot()) continue;
print $file->getFilename() . '<br>';
}
scandir
用法:
scandir
usage:
$files = scandir('.');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
opendir
和readdir
用法:
opendir
and readdir
usage:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
closedir($handle);
}
glob
用法:
glob
usage:
foreach (glob("*") as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
如评论中所述,glob
很不错,因为我在那里使用的星号实际上可以用于对文件进行匹配,因此glob('*.txt')
会为您提供文件夹中的所有文本文件,而glob('image_*')
会为您提供获取所有以image _
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_
这篇关于获取目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!