Monday, November 18, 2024
Google search engine
HomeLanguagesPHP | opendir() Function

PHP | opendir() Function

The opendir() function in PHP is an inbuilt function which is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.

The opendir() function is used to open up a directory handle to be used in subsequent with other directory functions such as closedir(), readdir(), and rewinddir().

Syntax:

opendir($path, $context)

Parameters Used: The opendir() function in PHP accepts two parameters.

  • $path : It is a mandatory parameter which specifies the path of the directory to be opened.
  • $context : It is an optional parameter which specifies the behavior of the stream.

Return Value: It returns a directory handle resource on success, or FALSE on failure.

Errors And Exceptions:

  1. A PHP error of level E_WARNING is generated and opendir() returns FALSE if the path is not a valid directory or the directory cannot be opened due to permission restrictions or filesystem errors.
  2. The error output of opendir() can be suppressed by prepending ‘@’ to the front of the function name.

Below programs illustrate the opendir() function:
Program 1:




<?php
  
// Opening a directory
$dir_handle = opendir("/user/gfg/docs/");
  
if(is_resource($dir_handle))
    echo("Directory Opened Successfully.");
  
// closing the directory
closedir($dir_handle);
  
else
{
    echo("Directory Cannot Be Opened.");
  
?>


Output:

Directory Opened Successfully.

Program 2:




<?php
  
// opening a directory and reading its contents
$dir_handle = opendir("user/gfg/sample.docx");
  
if(is_resource($dir_handle)) 
    while(($file_name = readdir($dir_handle)) == true) 
    
        echo("File Name: " . $file_Name);
        echo "<br>"
    
  
    // closing the directory
    closedir($dir_handle);
}
else
{
echo("Directory Cannot Be Opened.");
}
?>


Output:

File Name: sample.docx

Reference: http://php.net/manual/en/function.opendir.php

RELATED ARTICLES

Most Popular

Recent Comments