Using PHP rmdir() to Delete Empty Directories

This article explains the PHP rmdir() function, 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

The rmdir() function in PHP is used to delete a specified directory and is commonly employed when handling files and directories.

Syntax:

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

Parameters:

path

: The directory path to delete (required). It can be an absolute or relative path. context: Optional stream context resource.

Return Value:

If the directory is successfully deleted, true is returned; otherwise false is returned.

Important Notes:

The directory must be empty; otherwise the deletion will fail. To remove a non‑empty directory, first delete all its files and sub‑directories, then call rmdir() on the now‑empty directory.

Code Example:

The following example demonstrates how to use rmdir() to delete an empty directory after checking that it exists.

$dir = 'path/to/directory';

// Check if the directory exists
if (is_dir($dir)) {
    // Attempt to delete the directory
    if (rmdir($dir)) {
        echo "Directory deleted successfully.";
    } else {
        echo "Failed to delete directory.";
    }
} else {
    echo "Directory does not exist.";
}

In this example, is_dir() verifies the directory's existence, and rmdir() attempts to remove it, outputting a success or failure message accordingly. Remember that rmdir() can only delete empty directories; for non‑empty directories you must first remove their contents.

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.

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

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.