Php Directory Functions Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement PHP Directory Functions

Example 1: Creating a Directory

Let's start with creating a directory. We'll use the mkdir() function for this purpose.

<?php
// Define the directory name
$dirName = 'myNewDirectory';

// Create directory with 0755 permissions
if (mkdir($dirName, 0755, true)) {
    echo "Directory '$dirName' created successfully.";
} else {
    echo "Failed to create directory '$dirName'.";
}
?>

Explanation:

  • mkdir($dirName, 0755, true): This function attempts to create a directory named myNewDirectory. The 0755 permission mode specifies permissions for the directory. The true parameter allows us to create nested directories if they don't exist.

Example 2: Reading Files and Subdirectories in a Directory

Next, we will read all files and subdirectories within a directory. We'll use the scandir() function for this purpose.

<?php
// Define the directory name
$dirName = 'myNewDirectory';

// Check if directory exists
if (is_dir($dirName)) {
    // Read the directory
    $files = scandir($dirName);

    // List all files and directories
    echo "Files and directories in '$dirName':<br>";
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Directory '$dirName' does not exist.";
}
?>

Explanation:

  • scandir($dirName): This function reads the contents of the directory myNewDirectory and returns an array of filenames and subdirectory names.
  • is_dir($dirName): This function checks if the directory exists before attempting to read it.

Example 3: Removing a Directory

Finally, let's remove a directory. We'll use the rmdir() function to remove an empty directory, or use a recursive function to remove a non-empty directory.

<?php
function deleteDirectory($dirName) {
    // Open the directory
    if (is_dir($dirName)) {
        $objects = scandir($dirName);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (is_dir($dirName . DIRECTORY_SEPARATOR . $object)) {
                    // Recursively delete subdirectories
                    deleteDirectory($dirName . DIRECTORY_SEPARATOR . $object);
                } else {
                    // Delete files
                    unlink($dirName . DIRECTORY_SEPARATOR . $object);
                }
            }
        }
        // Remove the directory itself
        rmdir($dirName);
        return true;
    } else {
        return false;
    }
}

// Define the directory name
$dirName = 'myNewDirectory';

// Delete the directory
if (deleteDirectory($dirName)) {
    echo "Directory '$dirName' deleted successfully.";
} else {
    echo "Failed to delete directory '$dirName'.";
}
?>

Explanation:

  • deleteDirectory($dirName): This function is a recursive function that first scans the directory, then deletes all files and subdirectories, and finally removes the directory itself.
  • rmdir($dirName): This function removes an empty directory.
  • unlink($filePath): This function deletes a file.

Top 10 Interview Questions & Answers on PHP Directory Functions

PHP Directory Functions: Top 10 Questions and Answers

1. What is opendir() in PHP?

Answer:
opendir() is a PHP function used to open a directory handle that allows you to read from the specified directory. The syntax is as follows:

$handle = opendir('/path/to/directory');

You then use other functions like readdir(), closedir(), and optionally rewinddir() to interact with the directory contents.

2. How do I read all files from a directory using PHP?

Answer:
You can utilize opendir() and readdir() to read all files from a directory. A typical implementation is:

$directory = '/path/to/directory';
if (is_dir($directory)) {
    if ($handle = opendir($directory)) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                echo "$entry\n";
            }
        }
        closedir($handle);
    }
}

This code snippet opens a directory, reads its contents, and prints each entry’s name excluding the current (.) and parent (..) directories.

3. Can I filter only files (and not subdirectories) from a directory listing in PHP?

Answer:
Yes, you can filter out subdirectories by combining opendir(), is_file(), and scandir(). Here's an example using both approaches:

Using opendir():

if ($handle = opendir('/path/to/directory')) {
    while (false !== ($entry = readdir($handle))) {
        if (!in_array($entry, ['.','..']) && is_file("/path/to/directory/$entry")) {
            echo "$entry\n";
        }
    }
    closedir($handle);
}

Or directly using scandir() with array_filter():

$filesOnly = array_filter(scandir('/path/to/directory'), function ($item) {
    return !in_array($item, ['.','..']); // Filter out . and ..
}, ARRAY_FILTER_USE_BOTH);

foreach ($filesOnly as $entry) {
    if(is_file("/path/to/directory/$entry")) { 
        echo "$entry\n"; 
    }
}

Both methods will print only the files found in the directory.

4. How can I create a new directory in PHP?

Answer:
PHP makes it straightforward to create directories with the mkdir() function. Basic usage looks like this:

$dirname = "/path/to/new_directory";
if (!file_exists($dirname)) { // Check if directory does not already exist
    mkdir($dirname, 0755); // Create directory with permissions
}

The second parameter mode specifies the permission settings of the newly created directory.

5. What does rmdir() do and when is it used?

Answer:
The rmdir() function is used to remove an empty directory. If the directory has contents, rmdir() will return false. Example:

if (is_dir('/path/to/directory') && file_exists('/path/to/directory') && is_empty('/path/to/directory')) {
    rmdir('/path/to/directory');
}

function is_empty($dir) {
    return count(scandir($dir, SCANDIR_SORT_NONE)) === 2;
}

In this example, is_empty() checks if there are only two entries (which are always . and .. in an empty directory).

6. How can I delete a non-empty directory in PHP?

Answer:
To delete a non-empty directory, you need to recursively remove all files and subdirectories within it first. You can do this by traversing the directory tree, deleting files, and finally removing each subdirectory before removing the entire directory itself.

Here's a simple script to demonstrate how:

function rrmdir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != '.' && $object != '..') {
                if (is_dir($dir.'/'.$object))
                    rrmdir($dir.'/'.$object);
                else
                    unlink($dir.'/'.$object);
            }
        }
        rmdir($dir);
    }
}

// Usage
rrmdir('/path/to/directory');

7. How can I rename or move a directory in PHP?

Answer:
Renaming or moving a directory in PHP can be achieved using the rename() function, which works similarly for both files and directories:

$oldDirPath = '/path/to/old_directory'; 
$newDirPath = '/path/to/new_directory';

if (rename($oldDirPath, $newDirPath)) {
    echo "Directory renamed/moved successfully!";
} else {
    echo "Failed to rename/move directory.";
}

Remember, the path must be absolute or relative to your script’s location.

8. What function returns an array of directory contents in PHP?

Answer:
The scandir() function returns an array containing the names of the entries in the directory given by directory.

For example:

$files = scandir('/path/to/directory');
print_r($files);

This includes all files and directories including . and ... Optionally, flags like SCANDIR_SORT_ASCENDING or SCANDIR_SORT_DESCENDING can be passed to sort the result.

9. How do I find subdirectories within a directory in PHP?

Answer:
Scanning for only subdirectories in a directory can also be efficiently done using scandir() combined with is_dir(). Code snippet:

$parentDir = '/path/to/directory';
if (is_dir($parentDir)) {
    $subdirs = array_filter(scandir($parentDir), function ($item) use ($parentDir) {
        return !in_array($item, ['.','..']) && is_dir("$parentDir/$item"); 
    });
    print_r($subdirs);
} else {
    echo "Not a directory or doesn't exist!";
}

This script filters out everything except subdirectories.

10. Is there any way to copy a whole directory including its contents in PHP?

Answer:
Unfortunately, PHP doesn't provide a built-in function specifically for copying directories but you can implement a custom function to achieve this by recursively copying each file and subdirectory within the directory. Below is a sample recursive directory copy function:

function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ($file = readdir($dir))) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            } else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

// Usage
recurse_copy('/path/to/source_directory', '/path/to/destination_directory');

By creating a function like recurse_copy(), you can easily manage copying directories along with all their contents.

Conclusion

You May Like This Related .NET Topic

Login to post a comment.