Detailed explanation of the use of php dir() function

藏色散人
Release: 2023-04-06 09:54:02
Original
4199 people have browsed it

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)
Copy after login

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>" ;  
} 
  
?>
Copy after login

Output:

文件名称: gfg.jpg
文件名称: ..
文件名称: gfg.pdf
文件名称: .
文件名称: gfg.txt
Copy after login

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(); 
  
?>
Copy after login

Output:

目录路径: user/gfg
目录处理程序ID: Resource id #2

文件名称: gfg.jpg
文件名称: ..
文件名称: gfg.pdf
文件名称: .
文件名称: gfg.txt
Copy after login

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!

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 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!