Master PHP’s rmdir(): Delete Empty Directories Safely

This guide explains PHP’s rmdir() function, its syntax, parameters, return values, important usage notes, and provides a complete code example for safely removing empty directories, while warning about the need to clear non‑empty folders first.

php Courses
php Courses
php Courses
Master PHP’s rmdir(): Delete Empty Directories Safely

In PHP, the rmdir() function is used to delete a specified directory. It can only remove an empty directory.

Usage Syntax

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

Parameter Description

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

context : Optional stream context resource.

Return Value

The function returns true on successful deletion, or false on failure.

Notes

Ensure the directory is empty before calling rmdir(); otherwise the operation fails. To remove a non‑empty directory, first delete all its files and subdirectories, then call rmdir().

Code Example

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

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

Summary

The rmdir() function is a convenient way to delete directories in PHP, but it only works on empty directories. For non‑empty directories, clear their contents first before invoking rmdir().

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.

file 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.