How to Safely Delete Directories in PHP with rmdir()
This guide explains the PHP rmdir() function, its syntax, parameters, return values, important usage notes, and provides a complete code example for deleting empty directories while handling common pitfalls.
Overview
In PHP the rmdir() function removes a directory. It only works on empty directories; attempting to delete a non‑empty directory will fail.
Function Signature
bool rmdir ( string $path [, resource $context ] )Parameters
$path : The path of the directory to delete. Can be absolute or relative.
$context (optional): Stream context resource.
Return Value
Returns true on successful deletion, false otherwise.
Important Considerations
The directory must be empty. If it contains files or sub‑directories, you must first remove those items (e.g., by recursively deleting files) before calling rmdir().
Example 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.";
}Summary
The rmdir() function is a convenient way to delete empty directories in PHP. For non‑empty directories, clear their contents first, then call rmdir() to remove the directory itself.
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.
