How to work with Directories in PHP? See Examples

PHP provides several built-in functions to create, read, scan, and delete directories. Working with directories is essential when building file-management systems, upload handlers, backup utilities, and dynamic storage structures for your applications.

Below are the most commonly used directory functions and their practical usage.


Creating a Directory

To create a directory, PHP provides the mkdir() function.

Syntax

mkdir(string $directoryName, int $permissions = 0777, bool $recursive = false);

Example

<?php
$dir = "uploads/new_folder";

if (mkdir($dir)) {
    echo "Directory created successfully!";
} else {
    echo "Failed to create directory.";
}
?>

Important Notes

  • Permissions (like 0777) control read/write access.
  • Setting recursive = true allows creation of nested directories.

Checking if a Directory Exists

Before creating or using a directory, ensure it exists:

if (is_dir("uploads")) {
    echo "Directory exists.";
} else {
    echo "Directory not found.";
}

Reading a Directory

You can read directory contents using opendir(), readdir(), and closedir().

Example

<?php
$dir = "uploads";

if (is_dir($dir)) {
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            echo "Item: $file <br>";
        }
        closedir($handle);
    }
}
?>

Output

This will display:

.
..
image1.jpg
notes.txt
backup/

Scanning a Directory (Simpler Method)

PHP also provides scandir() to get directory items as an array.

$files = scandir("uploads");
print_r($files);

This outputs:

Array
(
    [0] => .
    [1] => ..
    [2] => image.jpg
    [3] => doc.pdf
)

Deleting a Directory

Use rmdir() to delete a directory, but only if it is empty.

Example

<?php
$dir = "uploads/old";

if (rmdir($dir)) {
    echo "Directory removed.";
} else {
    echo "Could not remove directory.";
}
?>

To delete a non-empty directory

You must remove all files inside first—PHP does not delete non-empty folders automatically.


Creating Nested Directories

mkdir("parent/child/grandchild", 0777, true);

Setting the third parameter (recursive) to true allows deep directory structures to be created in one line.


Changing the Current Directory

chdir("uploads");
echo getcwd();  // Shows the new current directory path

Getting the Current Working Directory

echo getcwd();

This returns the directory your script is currently running in.


Listing Only Files from a Directory

$items = scandir("uploads");

foreach ($items as $item) {
    if (is_file("uploads/" . $item)) {
        echo $item . "<br>";
    }
}

Listing Only Subdirectories

$items = scandir("uploads");

foreach ($items as $item) {
    if (is_dir("uploads/" . $item) && $item !== "." && $item !== "..") {
        echo $item . "<br>";
    }
}

Common Directory Handling Errors

Directory Does Not Exist

Always check using is_dir() before reading.

Permission Issues

Some directories do not allow creation or deletion without correct permissions (CHMOD 755/777).

Trying to Delete Non-Empty Directory

Use unlink() to remove files first, then rmdir().

Incorrect Path

Using relative vs absolute paths can cause confusion.


Practical Use Cases

Organizing uploads

Images/videos can be saved in date-wise directories such as uploads/2025/11/.

Backup and logs

Daily logs or backups are stored in separate folders.

Dynamic app folders

User-based file storage such as /users/user123/files/.


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *