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 == '..') {

        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.


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. MySQL value BETWEEN Two Columns in Laravel
  2. PHP tree structure for categories and sub categories without looping a MySQL query
  3. Email unique validation in Laravel ignore id on update
  4. WordPress Button Shortcode – Add button to WordPress editor
  5. WordPress shortcode – How to create shortcode in WordPress
  6. WordPress change URL in database using MySQL Query
  7. PHP remove HTML tags from string using strip_tags
  8. Enable shortcodes in widget WordPress
  9. PHP File upload step by step with example
  10. Laravel 6 integrate AdminLte admin theme jeroennoten

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 357 other subscribers

%d bloggers like this: