PHP remove non-empty directory programmatically

PHP remove non-empty directory programmatically

Today, We are going to learn PHP to remove non-empty directory. PHP provides rmdir function using that we can easily remove any directory. But When you are going to remove a non-empty directory using rmdir it’s fire exception. You can’t able to remove non-empty directory message something like The directory is not empty.

PHP remove non-empty directory

So Let’s see, how we can remove a non-empty directory. I am going to share function with you using that function you can able to remove a non-empty directory.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

First of all, Place this function with your code. Now, you just need to pass the directory path as a parameter to deleteDirectory function like.

deleteDirectory('folderPath');

Finally, Now you can able to remove a non-empty directory. You can get more detail about this function from here.

If you face any issue after using this function write the comment below.

Related Posts

  1. Email unique validation in Laravel ignore id on update
  2. WordPress Button Shortcode – Add button to WordPress editor
  3. WordPress shortcode – How to create shortcode in WordPress
  4. WordPress change URL in database using MySQL Query
  5. PHP remove HTML tags from string using strip_tags
  6. Enable shortcodes in widget WordPress
  7. PHP File upload step by step with example
  8. Laravel 6 integrate AdminLte admin theme jeroennoten
  9. WooCommerce add product to cart with custom price
  10. Laravel Eloquent where null and where not null query

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Search Posts

Subscribe To Newsletter

Get Early Access To New Articles, Plugins, Discount Codes And Quickly Brief Updates about tips and tricks

Join 308 other subscribers