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.
bool rmdir(string $path [, resource $context ])
If the directory is successfully deleted, rmdir() returns true; if it fails, it returns false.
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.
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.
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.