Backend Development 3 min read

Using PHP rmdir() to Delete Empty Directories: Syntax, Examples, and Precautions

This article explains how the PHP rmdir() function removes empty directories, provides its syntax and multiple code examples, and outlines important precautions such as permission requirements and the need for empty folders before deletion.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP rmdir() to Delete Empty Directories: Syntax, Examples, and Precautions

In PHP programming, removing a folder is a common task, and the rmdir() function is provided to delete empty directories.

Function Overview

The rmdir() function takes the directory path as its parameter and returns true on success and false on failure. Its basic syntax is:

<code>bool rmdir ( string $dirname [, resource $context ] )</code>

Usage Examples

Example 1 shows how to delete a single empty directory.

<code>$dir = "/path/to/directory";
if (rmdir($dir)) {
    echo "Folder deleted successfully!";
} else {
    echo "Folder deletion failed!";
}
</code>

Example 2 demonstrates deleting multiple directories in a loop.

<code>$dirs = array("/path/to/dir1", "/path/to/dir2", "/path/to/dir3");
foreach ($dirs as $dir) {
    if (rmdir($dir)) {
        echo "Folder deleted successfully!";
    } else {
        echo "Folder deletion failed!";
    }
}
</code>

Precautions

Only empty directories can be removed; any files or sub‑directories must be deleted first.

The executing user must have delete permissions for the target directory.

To remove non‑empty directories, a recursive approach must be used to delete contents before calling rmdir() .

Conclusion

The article explains the usage and important considerations of PHP’s rmdir() function, enabling developers to safely delete empty folders while being aware of permission and emptiness requirements.

Backendphpfile systemdirectory deletionrmdir
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.