Using PHP rmdir() to Delete Empty Directories
This article explains the PHP rmdir() function, detailing 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.
In PHP, the rmdir() function is used to delete a specified directory. It can only remove empty directories; attempting to delete a non‑empty directory will fail.
Usage Syntax:
<code>bool rmdir ( string $path [, resource $context ] )</code>Parameter Description:
$path : The path of the directory to delete (required). Can be absolute or relative.
$context : Optional stream context resource.
Return Value:
Returns true on successful deletion, or false on failure.
Notes:
Ensure the directory is empty before calling rmdir() . If it is not empty, you must first remove all files and sub‑directories, then invoke rmdir() again.
Code Example:
The following example demonstrates how to use rmdir() to delete an empty directory.
<code>$dir = 'path/to/directory';
// Check if the directory exists
if (is_dir($dir)) {
// Delete the directory
if (rmdir($dir)) {
echo "目录删除成功。";
} else {
echo "目录删除失败。";
}
} else {
echo "目录不存在。";
}
</code>In this example, is_dir() checks whether the target directory exists; if it does, rmdir() attempts to remove it, and the script outputs a success or failure message accordingly.
Summary
The rmdir() function is a convenient way to delete empty directories in PHP, but it cannot remove directories that contain files or sub‑directories; those must be cleared first.
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.