Using PHP rmdir() to Delete Empty Directories
This article explains the PHP rmdir() function, its syntax, parameters, return values, important usage notes, and provides a complete code example that checks for a directory's existence before safely removing an empty folder.
The rmdir() function in PHP is used to delete a specified directory and is commonly employed when handling files and directories.
Syntax:
<code>bool rmdir ( string $path [, resource $context ] )</code>Parameters:
path : The directory path to delete (required). It can be an absolute or relative path.
context : Optional stream context resource.
Return Value:
If the directory is successfully deleted, true is returned; otherwise false is returned.
Important Notes:
The directory must be empty; otherwise the deletion will fail. To remove a non‑empty directory, first delete all its files and sub‑directories, then call rmdir() on the now‑empty directory.
Code Example:
The following example demonstrates how to use rmdir() to delete an empty directory after checking that it exists.
<code>$dir = 'path/to/directory';
// Check if the directory exists
if (is_dir($dir)) {
// Attempt to delete the directory
if (rmdir($dir)) {
echo "Directory deleted successfully.";
} else {
echo "Failed to delete directory.";
}
} else {
echo "Directory does not exist.";
}
</code>In this example, is_dir() verifies the directory's existence, and rmdir() attempts to remove it, outputting a success or failure message accordingly. Remember that rmdir() can only delete empty directories; for non‑empty directories you must first remove their contents.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.