PHP Directory opendir() Function (With Examples)

In this tutorial, we will learn about the PHP opendir() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP opendir() function

The full form of opendir is "Open Directory", the function opendir() is used to open a directory.


The syntax of the opendir() function:



The parameters of the opendir() function:

  • path – It is the path (name) to the directory to be opened.
  • context – It is an optional parameter; it defines the context (a set of the options that can modify the behavior of the stream) of the directory handle.

Return Value

If function execution is success – it returns the directory handle resource if function execution is failed – it returns the "FALSE".

PHP opendir() Function Example

PHP code to open a directory, read its files, and close it.


$path = "/home";

//checking whether $path is a directory or not
//then, opening the directory and reading its files
if (is_dir($path)) {
    if ($dh = opendir($path)) {
        while (($file = readdir($dh)) !== false) {
            echo "File:" . $file . "<br/>";
        //closing the directory


The output of the above example is:


Reference: PHP opendir() function

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.