现在位置: 首页 > PHP 教程 > 正文

PHP scandir() 函数

PHP Directory PHP Directory 参考手册

实例

列出 images 目录中的文件和目录:

<?php
$dir = "/images/";

// Sort in ascending order - this is default
$a = scandir($dir);

// Sort in descending order
$b = scandir($dir,1);

print_r($a);
print_r($b);
?>

结果:

Array
(
[0] => .
[1] => ..
[2] => cat.gif
[3] => dog.gif
[4] => horse.gif
[5] => myimages
)
Array
(
[0] => myimages
[1] => horse.gif
[2] => dog.gif
[3] => cat.gif
[4] => ..
[5] => .
)


定义和用法

scandir() 函数返回指定目录中的文件和目录的数组。


语法

scandir(directory,sorting_order,context);

参数 描述
directory 必需。规定要扫描的目录。
sorting_order 可选。规定排列顺序。默认是 0,表示按字母升序排列。如果设置为 SCANDIR_SORT_DESCENDING 或者 1,则表示按字母降序排列。如果设置为 SCANDIR_SORT_NONE,则返回未排列的结果。
context 可选。规定目录句柄的环境。context 是可修改目录流的行为的一套选项。

技术细节

返回值: 成功则返回文件和目录的数组。失败则返回 FALSE。如果 directory 不是一个目录,则抛出 E_WARNING 级别的错误。
PHP 版本: 5.0+
PHP 更新日志: PHP 5.4:新增 sorting_order 常量。


PHP Directory PHP Directory 参考手册