Home >Backend Development >PHP Tutorial >Detailed explanation of the use of php dir() function
The dir() function in PHP is a built-in function that returns an instance of the directory class. The function of the dir() function is to read a directory, which includes the following content:
● Open the given directory.
● You can use the two attributes handle and path of dir().
● Both handle and path attributes have three methods: read(), rewind() and close().
The path to the directory is sent to the opendir() function as a parameter. If successful, it will return an instance of the directory class; if it fails, it will return FALSE.
Syntax:
dir($directory, $context)
Parameters:
The dir() function in PHP accepts two parameters, as described below .
$directory: It is a mandatory parameter that specifies the directory path.
$context: It is an optional parameter that specifies the behavior of the stream.
Return value:
Returns an instance of the directory class on success, and returns FALSE on failure.
Errors and exceptions:
If the passed dir() parameter is wrong, a NULL value is returned.
The order in which the read method returns directory entries depends on the system.
dir() function code example:
dir() function code example 1:
<?php $dir_handle = dir("user/gfg"); while(($file_name = $dirhandle->read()) !== false) { echo("文件名称 : " . $file_name); echo "<br>" ; } ?>
Output:
文件名称: gfg.jpg 文件名称: .. 文件名称: gfg.pdf 文件名称: . 文件名称: gfg.txt
dir() function code example 2:
<?php $dir_handle = dir("user/gfg"); echo("目录路径: " . $dir_handle->path . "<br>"); echo("目录处理程序ID: " . $dir_handle->handle . "<br>"); while(($file_name = $dir_handle->read()) !== false) { echo("File Name: " . $file_name); echo "<br>" ; } $dir_handle->close(); ?>
Output:
目录路径: user/gfg 目录处理程序ID: Resource id #2 文件名称: gfg.jpg 文件名称: .. 文件名称: gfg.pdf 文件名称: . 文件名称: gfg.txt
Related recommendations: "PHP Tutorial》
The above is the detailed content of Detailed explanation of the use of php dir() function. For more information, please follow other related articles on the PHP Chinese website!