In PHP, the rmdir()
If the directory is successfully deleted, rmdir() will return true; if the deletion fails, it will return false.
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.
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.
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.