
- PHP - Home
- PHP - Roadmap
- PHP - Introduction
- PHP - Installation
- PHP - History
- PHP - Features
- PHP - Syntax
- PHP - Hello World
- PHP - Comments
- PHP - Variables
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ and $$ Variables
- PHP - Constants
- PHP - Magic Constants
- PHP - Data Types
- PHP - Type Casting
- PHP - Type Juggling
- PHP - Strings
- PHP - Boolean
- PHP - Integers
- PHP - Files & I/O
- PHP - Maths Functions
- PHP - Heredoc & Nowdoc
- PHP - Compound Types
- PHP - File Include
- PHP - Date & Time
- PHP - Scalar Type Declarations
- PHP - Return Type Declarations
- PHP - Operators
- PHP - Arithmetic Operators
- PHP - Comparison Operators
- PHP - Logical Operators
- PHP - Assignment Operators
- PHP - String Operators
- PHP - Array Operators
- PHP - Conditional Operators
- PHP - Spread Operator
- PHP - Null Coalescing Operator
- PHP - Spaceship Operator
- PHP Control Statements
- PHP - Decision Making
- PHP - If…Else Statement
- PHP - Switch Statement
- PHP - Loop Types
- PHP - For Loop
- PHP - Foreach Loop
- PHP - While Loop
- PHP - Do…While Loop
- PHP - Break Statement
- PHP - Continue Statement
- PHP Arrays
- PHP - Arrays
- PHP - Indexed Array
- PHP - Associative Array
- PHP - Multidimensional Array
- PHP - Array Functions
- PHP - Constant Arrays
- PHP Functions
- PHP - Functions
- PHP - Function Parameters
- PHP - Call by value
- PHP - Call by Reference
- PHP - Default Arguments
- PHP - Named Arguments
- PHP - Variable Arguments
- PHP - Returning Values
- PHP - Passing Functions
- PHP - Recursive Functions
- PHP - Type Hints
- PHP - Variable Scope
- PHP - Strict Typing
- PHP - Anonymous Functions
- PHP - Arrow Functions
- PHP - Variable Functions
- PHP - Local Variables
- PHP - Global Variables
- PHP Superglobals
- PHP - Superglobals
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP File Handling
- PHP - File Handling
- PHP - Open File
- PHP - Read File
- PHP - Write File
- PHP - File Existence
- PHP - Download File
- PHP - Copy File
- PHP - Append File
- PHP - Delete File
- PHP - Handle CSV File
- PHP - File Permissions
- PHP - Create Directory
- PHP - Listing Files
- Object Oriented PHP
- PHP - Object Oriented Programming
- PHP - Classes and Objects
- PHP - Constructor and Destructor
- PHP - Access Modifiers
- PHP - Inheritance
- PHP - Class Constants
- PHP - Abstract Classes
- PHP - Interfaces
- PHP - Traits
- PHP - Static Methods
- PHP - Static Properties
- PHP - Namespaces
- PHP - Object Iteration
- PHP - Encapsulation
- PHP - Final Keyword
- PHP - Overloading
- PHP - Cloning Objects
- PHP - Anonymous Classes
- PHP Web Development
- PHP - Web Concepts
- PHP - Form Handling
- PHP - Form Validation
- PHP - Form Email/URL
- PHP - Complete Form
- PHP - File Inclusion
- PHP - GET & POST
- PHP - File Uploading
- PHP - Cookies
- PHP - Sessions
- PHP - Session Options
- PHP - Sending Emails
- PHP - Sanitize Input
- PHP - Post-Redirect-Get (PRG)
- PHP - Flash Messages
- PHP AJAX
- PHP - AJAX Introduction
- PHP - AJAX Search
- PHP - AJAX XML Parser
- PHP - AJAX Auto Complete Search
- PHP - AJAX RSS Feed Example
- PHP XML
- PHP - XML Introduction
- PHP - Simple XML Parser
- PHP - SAX Parser Example
- PHP - DOM Parser Example
- PHP Login Example
- PHP - Login Example
- PHP - Facebook Login
- PHP - Paypal Integration
- PHP - MySQL Login
- PHP Advanced
- PHP - MySQL
- PHP.INI File Configuration
- PHP - Array Destructuring
- PHP - Coding Standard
- PHP - Regular Expression
- PHP - Error Handling
- PHP - Try…Catch
- PHP - Bugs Debugging
- PHP - For C Developers
- PHP - For PERL Developers
- PHP - Frameworks
- PHP - Core PHP vs Frame Works
- PHP - Design Patterns
- PHP - Filters
- PHP - JSON
- PHP - Exceptions
- PHP - Special Types
- PHP - Hashing
- PHP - Encryption
- PHP - is_null() Function
- PHP - System Calls
- PHP - HTTP Authentication
- PHP - Swapping Variables
- PHP - Closure::call()
- PHP - Filtered unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - Expectations
- PHP - Use Statement
- PHP - Integer Division
- PHP - Deprecated Features
- PHP - Removed Extensions & SAPIs
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI Process
- PHP - PDO Extension
- PHP - Built-In Functions
PHP Directory dir() Function
The PHP Directory dir() Function is used to create an object of the directory class. It generates a directory class handle that can be used to read and rewind the directory's contents (files and folders). In addition to this we can also close the directory handle.
The dir() function opens a directory handle and returns an object. The object contains three methods namely −
- read(): To get a list of every file and folder in the directory-not the subfolders-use the read() function.
- rewind(): To begin the read() process again, use this function first.
- close(): To stop using the directory handle, use the close() function.
Syntax
Following is the syntax of the PHP Directory dir() Function −
dir(string $directory, ?resource $context = null): Directory|false
Parameters
Here are the required and optional parameters of the dir() function −
Sr.No | Parameter & Description |
---|---|
1 |
$directory(Required) The directory path to be opened. |
2 |
$context (Optional): A context stream resource. Default value is null. |
Return Value
The directory function dir() returns directory handle on success or FALSE on failure.
PHP Version
The dir() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7, PHP 8.
Example
Following is the basic example of the PHP Directory dir() function −
<php // Open the directory $directory = dir("/PhpProjects"); // Read entries while (($entry = $directory->read()) !== false) { // Print each entry echo $entry . "<br>"; } // Close the directory $directory->close(); ?>
Output
This will generate the following output −
. .. index.php README.md images css js
Example
In this PHP code example we will list the contents of a directory (/var/www in our case) using dir() function and show the information about each entry inside that directory. It reads each entry from the directory using a while loop. The loop runs until there are no more entries to read. After reading all the entries the directory handle is closed with the close() method.
<?php $d = dir("/var/www/"); echo "Handle: " . $d->handle . "\n"; echo "Path: " . $d->path . "\n"; while (false !== ($entry = $d->read())) { echo $entry."\n"; } $d->close(); ?>
This will produce the following result −
Handle: Resource id #5 Path: /var/www .. . html
Example
In this example we will show how we can use the dir() function in PHP to list the contents of a directory. So we will just open a directory called "new dir" which should be located in the current directory. It then lists all the contents of this directory (files and folders) and shows each entity's name as the outcome.
<?php // open the directory $directory_handle = dir("./new dir"); // check if the directory handle is valid or not if ($directory_handle) { echo "Contents of the directory:<br>"; // Loop over every entry in the directory while (($entry = $directory_handle->read()) !== false) { echo $entry . "<br>"; // Output each entry } // close the directory handle using close() $directory_handle->close(); } else { echo "Failed to open directory."; } ?>
Output
This will produce the below outcome −
Contents of the directory: . .. Pictures my_folder index.txt PHP my.txt
Example
In the below PHP code we will use all the three methods of dir class. So basically we will list the contents available in the given directory and rewind it using rewind() function and then close it using the close() function.
<?php $directory_handle = dir("./images/"); echo "Directory Handle: " . $directory_handle->handle . "<br>"; echo "Directory Path: " . $directory_handle->path . "<br>"; // loop to read and output each entry in the directory while ($entry = $directory_handle->read()) { echo "Entry: " . $entry . "<br>"; } // Rewind the directory handle to start reading from the beginning again $directory_handle->rewind(); // Loop again to read and output each entry in the directory while ($entry = $directory_handle->read()) { echo "Entry after rewind: " . $entry . "<br>"; } // Close the directory handle $directory_handle->close(); ?>
Output
This will generate the following output −
Directory Handle: Resource id #3 Directory Path: ./images/ Entry: . Entry: .. Entry: shankar.jpg Entry: robot.jpg Entry: hanuman.jpg Entry after rewind: . Entry after rewind: .. Entry after rewind: shankar.jpg Entry after rewind: robot.jpg Entry after rewind: hanuman.jpg
Summary
The dir() function in PHP opens a directory and returns a handle that can be used to view its contents. Use read() to iterate over the entries. To close, use close() function.
So we can say that this function is best for basic directory operations.