我正在寻找一个循环遍历目录中所有文件的PHP脚本,因此我可以使用文件名进行操作,例如格式化,打印或将其添加到链接中.我希望能够按名称,类型或创建/添加/修改日期对文件进行排序.(想想花哨的目录"索引".)我还希望能够在文件列表中添加排除项,例如脚本本身或其他"系统"文件.(就像.
和..
"目录"一样.)
由于我希望能够修改脚本,我更感兴趣的是查看PHP文档并学习如何自己编写.也就是说,如果有任何现有的脚本,教程和诸如此类的东西,请告诉我.
Mor*_*dur 229
您可以使用DirectoryIterator.php手册示例:
<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
?>
Run Code Online (Sandbox Code Playgroud)
Nex*_*Rex 41
如果您无权访问DirectoryIterator类,请尝试以下操作:
<?php
$path = "/path/to/files";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ('.' === $file) continue;
if ('..' === $file) continue;
// do something with the file
}
closedir($handle);
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 20
使用scandir()
功能:
<?php
$directory = '/path/to/files';
if (!is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ($file !== '.' && $file !== '..') {
$files[] = $file;
}
}
var_dump($files);
?>
Run Code Online (Sandbox Code Playgroud)
Jul*_*ian 11
你也可以利用FilesystemIterator
.它需要更少的代码然后DirectoryIterator
自动删除.
和..
.
// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');
$entries = array();
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
}
var_dump($entries);
//OUTPUT
object(FilesystemIterator)[1]
array (size=14)
0 => string 'aa[1].jpg' (length=9)
1 => string 'Chrysanthemum.jpg' (length=17)
2 => string 'Desert.jpg' (length=10)
3 => string 'giphy_billclinton_sad.gif' (length=25)
4 => string 'giphy_shut_your.gif' (length=19)
5 => string 'Hydrangeas.jpg' (length=14)
6 => string 'Jellyfish.jpg' (length=13)
7 => string 'Koala.jpg' (length=9)
8 => string 'Lighthouse.jpg' (length=14)
9 => string 'Penguins.jpg' (length=12)
10 => string 'pnggrad16rgb.png' (length=16)
11 => string 'pnggrad16rgba.png' (length=17)
12 => string 'pnggradHDrgba.png' (length=17)
13 => string 'Tulips.jpg' (length=10)
Run Code Online (Sandbox Code Playgroud)
链接:http: //php.net/manual/en/class.filesystemiterator.php
您可以使用此代码递归遍历目录:
$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
echo $file."\n";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
112393 次 |
最近记录: |