Directory Functions in PHP: A Complete Guide with Examples

Directory Functions in PHP: A Complete Guide with Examples

👋 Hey there, PHP developer! Working with files and folders is a crucial part of any programming language. In PHP, directory functions allow you to interact with directories—read contents, create folders, delete them, and more. If you’ve ever wanted to build a file manager, manipulate uploaded files, or simply organize server-side data, directory functions in PHP are your go-to tools.

In this blog post, we’ll walk through the most commonly used directory functions in PHP, explain how they work, and include practical code examples to help you implement them in real-world projects.

📁 What Are Directory Functions in PHP?

Directory functions in PHP are built-in functions that help you interact with folders on the server. They allow you to:

  • Open and read directory contents
  • Create and delete directories
  • Check for existence
  • Change current directories
  • Navigate through directories

Whether you’re developing a content management system (CMS) or handling user uploads, these functions come in handy.

Let’s dive into the most commonly used PHP directory functions.

📂 opendir() — Open a Directory

Description:

The opendir() function is used to open a directory handle for reading. This handle is later used with functions like readdir() and closedir().

Syntax:

PHP
opendir(string $directory, ?resource $context = null): resource|false

Example:

PHP
$dir = "uploads/";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        echo "Directory opened successfully.";
        closedir($dh);
    }
}

📄 readdir() — Read Files Inside a Directory

Description:

After opening a directory with opendir(), you can use readdir() to read its contents, one entry at a time.

Syntax:

PHP
readdir(?resource $dir_handle = null): string|false

Example:

PHP
$dir = "uploads/";

if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
        echo "File: " . $file . "<br>";
    }
    closedir($dh);
}

🔍 Note: . and .. are special directory entries representing the current and parent directories respectively.

📃 scandir() — Get All Directory Files as Array

Description:

The scandir() function returns an array of files and directories inside a specified path.

Syntax:

PHP
scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $context = null): array|false

Example:

PHP
$files = scandir("uploads/");

foreach ($files as $file) {
    echo $file . "<br>";
}

This is a simpler and faster alternative to using opendir() and readdir() if you want to get all files at once.

📁 mkdir() — Create a New Directory

Description:

The mkdir() function is used to create a new directory.

Syntax:

PHP
mkdir(
    string $directory,
    int $permissions = 0777,
    bool $recursive = false,
    ?resource $context = null
): bool

Example:

PHP
$newDir = "uploads/new_folder";

if (!file_exists($newDir)) {
    mkdir($newDir, 0755);
    echo "Directory created successfully.";
}

🛡️ Always check if the folder exists before creating one to avoid warnings or errors.

🗑️ rmdir() — Remove (Delete) a Directory

Description:

The rmdir() function removes an empty directory.

Syntax:

PHP
rmdir(string $directory, ?resource $context = null): bool

Example:

PHP
$dir = "uploads/old_folder";

if (is_dir($dir)) {
    rmdir($dir);
    echo "Directory deleted.";
}

⚠️ rmdir() only works on empty directories. To delete a directory with files, you need to remove its contents first.

📌 is_dir() — Check If Path is a Directory

Description:

This function is ued to checks if a given path is a directory or not.

Syntax:

PHP
is_dir(string $filename): bool

Example:

PHP
$path = "uploads/";

if (is_dir($path)) {
    echo "Yes, it's a directory.";
}

A helpful check before performing any directory-specific operations.

🔍 is_readable() and is_writable()

Description:

These functions check if the directory or file is readable or writable respectively.

Syntax:

PHP
is_readable(string $filename)
is_writable(string $filename)

Example:

PHP
$path = "uploads/";

if (is_readable($path)) {
    echo "Directory is readable.";
}

if (is_writable($path)) {
    echo "Directory is writable.";
}

Very useful for permission management on web servers.

🔄 chdir() — Change Current Directory

Description:

The chdir() function used to changes the current directory for the script.

Syntax:

PHP
chdir(string $directory): bool

Example:

PHP
chdir("uploads");
echo "Current Directory: " . getcwd();

🧭 Use getcwd() to get the current working directory path.

📌 glob() — Pattern Matching for Files

Description:

glob() searches for pathnames matching a specified pattern.

Syntax:

PHP
glob(string $pattern, int $flags = 0): array|false

Example:

PHP
$images = glob("uploads/*.jpg");

foreach ($images as $img) {
    echo $img . "<br>";
}

Very handy for filtering files with specific extensions.

🧹 Bonus: Delete Non-Empty Directory (Recursive Function)

Here’s a quick way to delete non-empty folders using recursion:

PHP
function deleteDir($dirPath) {
    if (!is_dir($dirPath)) return false;

    $items = scandir($dirPath);
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;
        $filePath = $dirPath . DIRECTORY_SEPARATOR . $item;

        if (is_dir($filePath)) {
            deleteDir($filePath);
        } else {
            unlink($filePath);
        }
    }
    return rmdir($dirPath);
}

🙋 Frequently Asked Questions

Can I delete a folder with files in PHP?

Yes, but not with rmdir(). You need to delete the files first (using unlink() or recursion) before removing the folder.

How can I list only .txt files in a directory?

Use glob("path/*.txt") to get an array of all .txt files in that path.

What’s the difference between readdir() and scandir()?

readdir() reads files one-by-one using a loop, while scandir() returns all files at once in an array.

✅ Summary Table

FunctionPurpose
opendir()Open a directory handle
readdir()Read files from directory
scandir()Get list of files as array
mkdir()Create new directory
rmdir()Delete an empty directory
is_dir()Check if a path is a directory
chdir()Change working directory
glob()Search with pattern

🎯 Final Thoughts

Working with directory functions in PHP is straightforward once you understand the flow—open, read, create, delete. These functions are not only useful but necessary when dealing with file uploads, CMS systems, or any server-side file management features.

Whether you’re just getting started with PHP or looking to sharpen your backend development skills, mastering these directory functions is a must.

Learn more about File Handling in PHP to combine file and directory operations smoothly.

Check the PHP Manual on Directory Functions for comprehensive documentation and edge cases.

If you found this article helpful, feel free to share it or leave a comment! Happy coding! 👨‍💻👩‍💻


Comments

Leave a Reply

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