PHP4与PHP5在列出目录中所有文件时的区别

PHP4要列出目录中所有文件,需要用到以下几个函数:
1.resource opendir ( string path )
此函数返回一个句柄,供后面的readdir()使用,其参数path便是要列出文件列表的目录,例出”/var/www”
2.string readdir ( resource dir_handle )
此函数目录中下一个文件(或目录)的文件(或目录)名。文件(或目录)名的顺序取决于系统中文件的排序。
例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< ?php
$path = "/var/www";
$files = array();
if ( $handle = opendir($path) ) {
while( false != ($file = readdir($handle) ) ) {
//判断条件一定要用false != ($file = readdir($handle) )
//而不能直接用$file = readdir($handle)
array_push($files, $file);
}
sort($files); //对取得的列表按字母顺序排一下序
}
 
print_r($files);
?>

PHP5比PHP4新增加了一个scandir()函数,专门用来列出目录中文件的,因此实现起来就要简单多了。scandir()的用法为:
array scandir ( string directory [, int sorting_order] )
它会直接返回一个包含directory中所有文件和目录的string型数组,而且已经是按字母升序排列好的。
它的第二个参数是可选的,用来控制排序方式,如果设置了其值为1,那么排序顺序则会使用字母降序。
例子:

1
2
3
4
5
6
< ?php
$path = "/var/www";
$files = scandir($path);
 
print_r($files);
?>

当然,在PHP5中,PHP4的方法仍然是可以使用的。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>