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

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

M66 2025-06-16

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

In PHP, the rmdir() function is used to delete a specified directory. It is a commonly used function, especially when dealing with file and directory operations. Note that rmdir() can only delete empty directories and cannot delete directories that contain files or subdirectories.

Usage Syntax:

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

Parameter Explanation:

  • path: The path of the directory to be deleted (required). It can be an absolute or relative path.
  • context: An optional parameter to specify the stream context.

Return Value:

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

Important Notes:

Before using rmdir() to delete a directory, make sure the directory is empty. If the directory is not empty, the delete operation will fail. To delete a non-empty directory, you must first remove all files and subdirectories within it, then call rmdir() to delete the directory itself.

Code Example:

Here is a simple example showing how to use rmdir() to delete an empty directory:

$dir = 'path/to/directory';
<p>// Check if the directory exists<br>
if (is_dir($dir)) {<br>
// Delete the directory<br>
if (rmdir($dir)) {<br>
echo "Directory deleted successfully.";<br>
} else {<br>
echo "Directory deletion failed.";<br>
}<br>
} else {<br>
echo "Directory does not exist.";<br>
}<br>

In this example, we first use the is_dir() function to check if the specified directory exists. If the directory exists, we call rmdir() to delete the directory. If the deletion is successful, the message “Directory deleted successfully” is output. If it fails, the message “Directory deletion failed” is displayed. If the directory does not exist, the message “Directory does not exist” is shown.

Summary:

The rmdir() function is a simple yet effective tool in PHP for deleting empty directories. In actual development, make sure the directory is empty before deletion. If you need to delete a non-empty directory, clear all files and subdirectories inside first, then call rmdir() to delete the directory itself.