PHP rmdir() | Remove Directory

The PHP rmdir() function is used when we need to delete or remove a directory. For example:

   $directory = "Documents";
   $ch = rmdir($directory);
      echo "<p>The directory deleted successfully</p>";
      echo "<p>Unable to delete the directory</p>";

The output of the above PHP example using the rmdir() function is shown in the following snapshot:

php rmdir function

Note: The directory will be removed only when the directory is completely empty.

The above output is produced because, inside my current directory, there is a folder or directory named "Documents" that is, of course, empty.

PHP rmdir() Syntax

The syntax of the rmdir() function in PHP is:

rmdir(directory, context)

The first parameter (directory) is required, whereas the last parameter (context) is optional and is used to specify the context resource while removing an empty directory.

PHP rmdir() function example

Consider the following PHP code as an example demonstrating the rmdir() function:

   $dir_path = "xyz";

   // Before attempting to remove a directory, ensure that it exists.
   if (is_dir($dir_path)) {
      if (rmdir($dir_path)) {
         echo "The directory was successfully removed.";
      } else {
         echo "Unable to remove directory";
   } else {
      echo "Directory does not exist";

The step-by-step explanation of the above PHP example is as follows:

Advantages of the rmdir() function in PHP

Disadvantages of the rmdir() function in PHP

PHP Online Test

« Previous Tutorial Next Tutorial »

Liked this post? Share it!