Current Location: Home> Latest Articles> PHP rmdir() Function Explained: How to Delete Empty Directories

PHP rmdir() Function Explained: How to Delete Empty Directories

gitbox 2025-06-16

PHP rmdir() Function Explained: How to Delete Empty Directories

In PHP, the rmdir()

Parameter Explanation

  • $path: The path to the directory to be deleted. It can be either an absolute or relative path.
  • $context: An optional parameter that specifies the stream context.

Return Value of rmdir() Function

If the directory is successfully deleted, rmdir() will return true; if the deletion fails, it will return false.

Considerations when Using rmdir()

Before using rmdir() to delete a directory, make sure the directory is empty. If the directory is not empty, the deletion will fail. To delete a non-empty directory, you need to first clear the contents of the directory (including files and subdirectories), and then call rmdir() to delete the directory itself.

Code Example of rmdir() Function

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

$dir = 'path/to/directory';

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

In this example, we first check if the specified directory exists using the is_dir() function. If the directory exists, we proceed to delete it using rmdir(), and output appropriate messages based on whether the deletion was successful or not.

Conclusion

The rmdir() function is a simple yet useful tool in PHP for deleting empty directories. However, it can only delete directories that are empty. If you need to delete a non-empty directory, you must first remove its contents before calling rmdir() to delete the directory itself.