Home >Backend Development >PHP Tutorial >Usage instructions of php readdir() function

Usage instructions of php readdir() function

怪我咯
怪我咯Original
2017-07-10 15:57:272574browse

readdir() FunctionReturns the file name of the next file in the directory. Returns the entry name (file name) on success, or FALSE on failure.

Syntax

readdir(dir_handle);
Parameters Description
##dir_handle Optional. Specifies a directory handle resource previously opened by

opendir().

If this parameter is not specified, the last link opened by opendir() is used.

readdir() Function example one, the code is as follows:

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

readdir() Function example two, the code is as follows:

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() Function Example 3, readdir() will return . and .. entries. If you don’t want them, just filter them out. Example 2. List all files in the current directory and remove . and .., code As follows:

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

Note:

readdir must be used in conjunction with opendir.

The above is the detailed content of Usage instructions of php readdir() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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