Skip to content

opendir()

What is opendir() Function in PHP?

opendir() is a built-in function in PHP that opens a directory handle for a specific path. It is used to traverse through the contents of a directory and perform various operations on them.

Syntax

The syntax for using the opendir() function is as follows:

Syntax of PHP opendir() function

php
Directory|false opendir ( string $path [, resource $context ] )

Where:

  • $path is the directory path you want to open.
  • $context is an optional parameter that allows you to specify additional context for the stream.

Note: In PHP 8.0+, opendir() returns a Directory object instead of a resource.

How to Use opendir() Function?

To use the opendir() function, you first need to specify the path of the directory you want to open. Once you have the path, you can use the function to open the directory handle. Here's an example:

How to Use opendir() Function?

php
<?php

$dir = "/path/to/directory";
$dh = opendir($dir);

if ($dh === false) {
    echo "Failed to open directory.";
}

This code opens the directory at the specified path and assigns the directory handle to the $dh variable.

How to Traverse through Directories?

Once you have opened the directory handle, you can use the readdir() function to read the contents of the directory. Here's an example:

Example of opendir() function in PHP

php
<?php
while (($file = readdir($dh)) !== false) {
    echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}

This code reads the contents of the directory and outputs the name and type of each file.

Closing the Directory Handle

After you have finished working with the directory, you should close the directory handle using the closedir() function. Here's an example:

Example of using closedir() function in PHP

php
<?php
closedir($dh);

Conclusion

In conclusion, the opendir() function is an important function in PHP that is used to open a directory handle and traverse through the files and directories within a directory. We hope this guide has been helpful in understanding how to use the opendir() function effectively in your code.

With this guide, you can now use the opendir() function with confidence and improve the functionality of your PHP code.

Practice

What does the opendir() function in PHP do?

Dual-run preview — compare with live Symfony routes.