兼容PHP5的目录管理函数库详解
本工具库主要支持的环境为:PHP 5
一、chdir -- 改变目录
语法:bool chdir ( string directory )
返回值:布尔值
函数种类: 文件存取
内容说明:
该函数用于将 PHP 脚本的当前工作目录更改为指定的 directory 参数。若操作成功,函数返回 TRUE;若失败,则返回 FALSE。
例子讲解:
程序代码
<?php
// current directory
echo getcwd() . "\n";
chdir('public_html');
// current directory
echo getcwd() . "\n";
?> 输出结果为:
/home/vincent
/home/vincent/public_html
注意:在循环语句中执行此操作时,可能会触发 “Warning: chdir(): No such file or directory (errno 2) in ***** on line *” 的错误提示。
程序代码
<?php
// current directory
echo getcwd() . "\n";
for($i=1; $i<=2; $i++){
chdir('whoist');
// current directory
echo getcwd() . "\n";
}
?> 二、dir -- directory 类
语法:new dir(string directory);
返回值:对象实例
函数种类: 文件存取
内容说明:
这是一个面向对象的目录读取类。当传入的 directory 参数被成功打开后,可通过两个属性访问:handle 属性类似于传统非类函数中的 readdir()、rewinddir() 及 closedir() 所使用的资源句柄;path 属性则存储打开目录后的路径字符串。该类提供三个方法:read、rewind 与 close。
class dir {
dir ( string directory )
string path
resource handle
string read ( void )
void rewind ( void )
void close ( void )
}
例子讲解:
程序代码
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?> 输出结果为:
Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli
注: read 方法返回的目录项顺序取决于底层操作系统。
注: 本函数定义了内部类 Directory,因此用户不得使用相同的名称定义自己的类。
三、closedir -- 关闭目录句柄
语法:void closedir ( resource dir_handle )
返回值:无
函数种类: 文件存取
内容说明:
用于关闭由 dir_handle 指定的目录流。该句柄必须此前已通过 opendir() 函数打开。
例子讲解:
程序代码
<?php
$dir = "/etc/php5/";
// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$directory = readdir($dh);
closedir($dh);
}
}
?> 四、opendir -- 打开目录句柄
语法:resource opendir ( string path [, resource context] )
返回值:资源或布尔值
函数种类: 文件存取
内容说明:
此函数用于打开一个目录资料流。成功时返回一个可供其他目录函数(如 closedir()、readdir() 和 rewinddir())操作的资源句柄;失败时返回 FALSE。
例子讲解:
程序代码
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?> 输出结果为:
filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir