Home >Backend Development >PHP Tutorial >Usage instructions of php readdir() function
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. |
$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!