Using PHP rmdir() to Delete Empty Directories

This article explains the PHP rmdir() function, detailing its syntax, parameters, return values, important usage notes, and provides a complete code example that checks for a directory’s existence before safely removing an empty folder.

php Courses
php Courses
php Courses
Using PHP rmdir() to Delete Empty Directories

In PHP, the rmdir() function is used to delete a specified directory. It can only remove empty directories; attempting to delete a non‑empty directory will fail.

Usage Syntax:

bool rmdir ( string $path [, resource $context ] )

Parameter Description:

$path : The path of the directory to delete (required). Can be absolute or relative.

$context : Optional stream context resource.

Return Value:

Returns true on successful deletion, or false on failure.

Notes:

Ensure the directory is empty before calling rmdir(). If it is not empty, you must first remove all files and sub‑directories, then invoke rmdir() again.

Code Example:

The following example demonstrates how to use rmdir() to delete an empty directory.

$dir = 'path/to/directory';

// Check if the directory exists
if (is_dir($dir)) {
    // Delete the directory
    if (rmdir($dir)) {
        echo "目录删除成功。";
    } else {
        echo "目录删除失败。";
    }
} else {
    echo "目录不存在。";
}

In this example, is_dir() checks whether the target directory exists; if it does, rmdir() attempts to remove it, and the script outputs a success or failure message accordingly.

Summary

The rmdir() function is a convenient way to delete empty directories in PHP, but it cannot remove directories that contain files or sub‑directories; those must be cleared first.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPdirectory 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

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.