PHP中的scandir()函数是一个内置函数,用于返回指定目录的文件和目录数组。 scandir()函数列出了指定路径中存在的文件和目录。
文件和目录的目录,流行为以及sorting_order作为参数传递给scandir()函数,如果成功,则返回文件名数组;如果失败,则返回False。
用法:
scandir(directory, sorting_order, context);
使用的参数:
PHP中的scandir()函数接受三个参数。
directory:这是指定路径的必需参数。
sorting_order:这是一个可选参数,用于指定排序顺序。默认排序顺序为按字母顺序升序(0)。可以将其设置为SCANDIR_SORT_DESCENDING或1以按字母降序排列,或设置为SCANDIR_SORT_NONE以返回未排序的结果。
context:这是一个可选参数,用于指定流的行为。
返回值:成功返回一个文件名数组,失败返回False。
错误与异常
如果指定的目录不是目录,则scandir()函数将引发E_WARNING级别的错误。
在具有许多文件的目录上执行递归scandir,这可能会导致应用程序变慢或由于生成的数组较大而导致RAM消耗大量增加。
以下示例程序旨在说明scandir()函数:
程序1
// specifying directory
$mydir = '/docs';
//scanning files in a given diretory in ascending order
$myfiles = scandir($mydir);
//displaying the files in the directory
print_r($myfiles);
?>
输出:
(
[0] => .
[1] => ..
[2] => aboutus.php
[3] => contact.php
[4] => index.php
[5] => terms.php
)
程序2
// specifying directory
$mydir = '/docs';
//scanning files in a given diretory in descending order
$myfiles = scandir($mydir, 1);
//displaying the files in the directory
print_r($myfiles);
?>
输出:
Array
(
[0] => terms.php
[1] => index.php
[2] => contact.php
[3] => aboutus.php
[4] => ..
[5] => .
)
程序3
// specifying directory
$mydir = '/docs';
//scanning files in a given diretory in unsorted order
$myfiles = scandir($mydir, SCANDIR_SORT_NONE);
//displaying the files in the directory
print_r($myfiles);
?>