Home > php教程 > php手册 > body text

php之readdir函数用法实例

WBOY
Release: 2016-06-06 20:17:38
Original
1223 people have browsed it

这篇文章主要介绍了php中readdir函数用法,以实例讲述了readdir函数操作目录的具体用法与相关的注意事项,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php中readdir函数用法。分享给大家供大家参考。具体用法分析如下:

定义和用法:readdir() 函数返回由 opendir() 打开的目录句柄中的条目,若成功,则该函数返回一个文件名,否则返回 false.

实例一,代码如下:

复制代码 代码如下:

$dir = "readdir/";
 
// 判断是否为目录
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . " ";
        }
        closedir($dh);
    }
}


实例二,注意在 4.0.0-RC2 之前不存在 !== 运算符,代码如下:

复制代码 代码如下:

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle ";
    echo "Files: ";
 
    /* 这是正确地遍历目录方法 */
    while (false !== ($file = readdir($handle))) {
        echo "$file ";
    }
 
    /* 这是错误地遍历目录的方法 */
    while ($file = readdir($handle)) {
        echo "$file ";
    }
    closedir($handle);
}


实例三,readdir() 将会返回 . 和 .. 条目,如果不想要它们,只要过滤掉即可,例子 2. 列出当前目录的所有文件并去掉 . 和 ..,代码如下:

复制代码 代码如下:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file ";
        }
    }
    closedir($handle);
}


注:readdir必须与opendir配合使用才行.

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!