259 of 410 menu

The rmdir Function

The rmdir function removes the specified directory. The directory must be empty and the script must have write permissions to the parent directory. The function takes one required parameter - the path to the directory.

Syntax

rmdir(string $directory, resource $context = ?): bool

Example

Removing an empty directory:

<?php $dir = 'empty_folder'; if (rmdir($dir)) { echo "Directory $dir was successfully removed"; } else { echo "Failed to remove directory $dir"; } ?>

Code execution result:

'Directory empty_folder was successfully removed'

Example

Attempting to remove a non-empty directory:

<?php $dir = 'non_empty_folder'; if (@rmdir($dir)) { echo "Directory $dir was removed"; } else { echo "Cannot remove $dir - directory is not empty"; } ?>

Code execution result:

'Cannot remove non_empty_folder - directory is not empty'

Example

Checking if a directory exists before removal:

<?php $dir = 'temp_folder'; if (is_dir($dir)) { if (rmdir($dir)) { echo 'directory removed successfully'; } else { echo 'failed to remove directory'; } } else { echo 'directory does not exist'; } ?>

Code execution result:

'directory removed successfully'

See Also

  • the mkdir function,
    which creates a directory
  • the unlink function,
    which deletes a file
  • the scandir function,
    which reads the contents of a directory
byenru