Skip to content

rmdir()

Introduction

In PHP, the rmdir() function is used to remove a directory. It is a useful function for managing your file system. In this article, we will cover everything you need to know about the rmdir() function, including its syntax, parameters, and examples of how it can be used.

Understanding the rmdir() Function

The rmdir() function in PHP is used to remove a directory. It takes a single parameter, which is the name of the directory to be removed.

The rmdir() function only removes empty directories. If the directory contains files or subdirectories, or if the script lacks the necessary permissions, the operation will fail and emit a warning.

Syntax of the rmdir() Function

The syntax of the rmdir() function is as follows:

Syntax of the rmdir() Function

php
rmdir($directory);

Here, $directory is the name of the directory to be removed. The function returns true on success and false on failure.

Examples of Using rmdir()

Let's take a look at an example of how the rmdir() function can be used in PHP.

Example 1: Removing a Directory

Examples of Using rmdir()

php
<?php

$directory = 'example_directory';
if (is_dir($directory)) {
    if (rmdir($directory)) {
        echo "Directory removed successfully.";
    } else {
        echo "Failed to remove directory. It may not be empty or lack permissions.";
    }
}

This example checks if the example_directory directory exists using the is_dir() function. If it exists, the rmdir() function is used to remove the directory, with error handling to catch failures.

Example 2: Removing a Non-Empty Directory

Since rmdir() cannot delete directories containing files, you must remove the contents first. A common approach is to use a recursive function:

php
<?php

function removeDirectory($dir) {
    if (!is_dir($dir)) {
        return false;
    }
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        is_dir($path) ? removeDirectory($path) : unlink($path);
    }
    return rmdir($dir);
}

removeDirectory('example_directory');

Conclusion

The rmdir() function provides a straightforward way to remove empty directories in PHP. We hope that this article has given you a better understanding of how rmdir() works and how it can be used in your own projects.

Practice

What is the purpose of the rmdir() function in PHP?

Dual-run preview — compare with live Symfony routes.