PHP rmdir() Function: Deleting Directories

The PHP rmdir() function removes an empty directory with proper permissions, returning TRUE on success or FALSE on failure, and the article explains its parameters, return values, and provides cross‑platform code examples for safely deleting directories.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP rmdir() Function: Deleting Directories

The rmdir() function in PHP attempts to delete the directory specified by $dirname; the directory must be empty and the script must have the necessary permissions. On success it returns TRUE, otherwise FALSE and triggers an E_WARNING error.

Parameters string $dirname – Path of the directory to be removed. resource $context – Optional context resource for stream operations.

Return value

Returns TRUE on success, FALSE on failure.

Example 1

<?php
if (!is_dir('examples')) {
    mkdir('examples');
}
 rmdir('examples');
?>

This example creates a directory named examples and then removes it using rmdir().

Example 2

<?php
if (PHP_OS === 'Windows') {
    exec(sprintf('rd /s /q %s', escapeshellarg($path)));
} else {
    exec(sprintf('rm -rf %s', escapeshellarg($path)));
}
?>

The second example demonstrates a cross‑platform approach: on Windows it runs rd /s /q, while on Unix‑like systems it uses rm -rf to delete the directory.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPFilesystemdirectory deletionrmdir
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.