Enjoy what you read, learn from the tips with tricks and join in the chats with your comments. Suggest posts, articles or even submit your own stuff and get yourself a FREE Featured Post or FREE Portfolio section on my blog.

A PHP Guide – Delete directory and contents – Walkthrough
31 Jan 2012

A PHP Guide – Delete directory and contents – Walkthrough

In this fantastic tutorial we are going to be looking at creating a function that deletes a directory that has contents.

Now we do have a function in PHP already which is called rmdir() so lets just take a minute and take a look at what this function would look like.

<?php
rmdir('directory_name');
?>

Inside the rmdir brackets between the quotes you would place your directory name of the folder you want to delete. Now this can be very useful if you are storing say images inside a directory for a particular user or some type of product line.

There are a variety of reasons why you would use the rmdir() function, however if a directory has file contents then PHP will not be able to delete the directory and you will get an error message appear.

If you want to know more about ‘functions’ and using them before you carry on then check out my previous articles on PHP Coding Made Easier – Using Functions, PHP Coding Made Easier – Using Variables in Functions otherwise lets carry on. ;)

So we need a way to solve this and today we are going to be creating our own function and this is going to be a ‘recursive function’ which is going to reference itself. I suggest you read up more on recursion so you are familiar with the concept but its not necessary in-order to complete this PHP Snippet.

A good place to start is this site: Fundamentals of Recursion in PHP.

Basically, recursion is something that references itself so hopefully that has saved you about 30mins research time. :) In this case it will essentially be calling itself to loop through or scan through the directory or a file structure of a particular directory and delete everything within.

If you need to know more about using ‘loops’ in PHP then check out my previous articles by clicking:

So this will not just delete a folder with contents it will delete folders with perhaps folders within folders with folders having contents within folders. :) So the best way explain this is to show you en example. So as it stands this function rmdir() is part of the default PHP Function set.

So first of all on your localhost or remote server you will need to create a directory called ‘vose’ which needs to be in the same place as the file we are going to be working on today. To show you how simple it is to remove a directory create a PHP file called ‘index.php’ and copy the following code into it then upload the file to the same location as your ‘vose’ folder you have created. (Do not put the ‘index.php’ file inside your ‘vose’ folder otherwise it wont work. :)

<?php
rmdir('vose');
?>

You should see that your newly created ‘vose’ directory has now been removed from your localhost or your remote server. Its that simple to remove a directory but remember that if your directory has any contents within it your PHP rmdir() function will return an error.

Now, lets go ahead and create that directory again on your localhost or remote server called ‘vose’ but this time we are going to create a file inside of it.

So create a ‘text_1.txt’ document inside the folder. You do not need to type anything within the file because we are just going to see what PHP has to say about that file we have now created in our directory.

Now go back to your browser and refresh your ‘index.php’ page and you will see a warning appear on your screen stating that your directory is not empty. You can see that this is a warning message which means it has not actually error-ed so it will execute the rest of our code if we had some but it will not delete the directory because it does not know what to do with the directories contents.

As you can see this is a bit of a pain when trying to delete directories but we can solve this by creating our own function. This function can be included within say a global function file that you access across your whole website from each page.

So before we get started in creating our function you will need to create another text file called ‘text_2.txt’ within your ‘vose’ directory, then you can create a sub directory within your ‘vose’ folder called ‘sub_vose’. Now within your sub directory you can create another text file and call this ‘text_3.txt’. You should now have your original directory (vose) with 2 text files inside (1 & 2) then a sub directory (sub_vose) and within that sub directory you should have 1 text file (3). If you want to you can create another sub directory within your ‘sub_vose’ called ‘sub_vose_2′ and create another text file called ‘text_4.txt’ so that we have multiple sub directories and files which will really show our script works. :)

Essentially we are asking our function to not just delete files within our directory but actually look inside sub directories and delete files within that and also delete the sub directory folder and also the folder we originally accessed. So lets get back to our code and we will start to write this function out.

I am going to call this function ‘vose_remove_directory’ and we start our code like this:

<?php
function vose_remove_directory() {

}
?>

We need to set a parameter which we will call the ‘directory’ and we code this by adding the string variable between the brackets like so:

<?php
function vose_remove_directory($directory) {

}
?>

The first thing we will want to do with our function is to check to see if this is actually a directory and we can do this by creating an if statement inside our function. Which would look like this:

<?php
function vose_remove_directory($directory) {
    if () {
	
	}
}
?>

Between the if statement brackets we can use the is_dir() function that PHP provides for us and we need to set the parameter to our string variable $directory like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory)) {
	
	}
}
?>

Now outside our function we are going to call this function to use and test it like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory)) {
	
	}
}

vose_remove_directory('vose'); // notice the name of our directory between the brackets
?>

We already have the directory called ‘vose’ so what will happen is our call script we just added will pass our ‘vose’ text (name of directory) in to our string variable $directory and then it will say: is $directory an actual directory. So to see an example of this we need to create the equals statement to check if this is true and if true we can echo the text ‘Directory Exists’ on our screen like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   echo 'Directory Exists';
	}
}

vose_remove_directory('vose'); // notice the name of our directory between the brackets
?>

Now if you go back to your browser and fresh your page you should see that the page displays the text ‘Directory Exists’. If it does not then you have not named the directory correctly or you have mistyped your directory name within your PHP code above. Make sure also that your ‘index.php’ file is in the same location as your ‘vose’ directory with all those files and sub directories you created earlier.

If your page does display ‘Directory Exists’ then well done. To test this code you can change the call script at the end to something other than ‘vose’ and you will see that the page does not display ‘Directory Exists’ because it does not. :) Do it like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   echo 'Directory Exists';
	}
}

vose_remove_directory('something_else_here'); // notice name of directory between brackets has changed
?>

Now we no longer need to really echo that text because within our function we can now create the code that will grab the entire contents of our directory for us. So lets go ahead and create a variable called $contents and we are going to use the scandir() function that PHP provides for us; then we set the parameter to $directory again.

For now I am going to return this statement so it will return an array with the contents of our directory. Then I can use the print_r() function which will provide me with the array data that our is_dir() has provided. We do this like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   return $contents = scandir($directory);
	}
}

print_r(vose_remove_directory('vose')); // notice name directory has changed back!
?>

Ok, now fire up your browser and click refresh to see what we have. You should see an array lke so:

Array ( [0]=>.[1]=>..[2]=>text_1.txt[3]=>text_2.txt[4]=>sub_vose )

Great, we now have our array. The first (0) is a dot and then a double dot (1) which is just basically part of the directory structure. Then we have ‘text_1.txt’, ‘text_2.txt’ and ‘sub_vose’ and this is now where we need to start thinking about recursion because if we come across a folder we would want to go and delete this folder as well and therefor we are going to have to go inside that folder and do the same process over again. If this does not seem clear at the moment to you then do not worry as it will start to become clear the further on into the code we get. :)

Remember this is not a particularly long function so it is not a difficult thing to code. So lets get back to our code and unset the first two results in our variable called ‘.’ and ‘..’ because they are just part of the directory structure. First, get rid of the return function at the beginning of our $contents variable. Next we want to use the unset for our $contents variable to say $contents[0] which is the first result in our array and $contents[1] which is our second result in our array. This tells PHP to ignore those first two results of our array as we do not want to do anything with those. Unset can have multiple parameters as you can see because we have used two in our current code. :)

Now we need to go ahead and return our $contents variable and we do this like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   return $contents;
	}
}

print_r(vose_remove_directory('vose'));
?>

If you now go back to your browser and refresh you will see that the first two results have been removed from the array as printed on your screen using our print_r() function. So now we are only working with our files and folders.

Ok, so now what we want to do is loop through the contents if the directory and base a decision on whether we want to first of all delete something, whether its a file or not because if its just a file we want to delete it and we can use the unlink() function to just do that. If the current object is however a directory(sub) we would need to apply the entire process over again to delete everything within it and the sub directory itself.

In order to accomplish this I am going to use a ‘foreach loop’ like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach() {
	   
	   }
	   
	}
}

print_r(vose_remove_directory('vose'));
?>

We now set the parameters of this foreach loop to $content as $object which will basically make each file and folder within our directory an $object. Then we will want to create a variable inside of this to represent the current object. We want to do that by taking the current directory we are in followed by forward slash followed by the object itself. Take a look:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      $current_object = $directory.'/'.$object;
	   }
	   
	}
}

print_r(vose_remove_directory('vose'));
?>

Now what I am going to do is just echo that line out and then append on a break at the end and this is going to just give me and idea as I am going along how everything is looking. So we do not need the print_r() function anymore because we are already going to output something using the echo statement like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      echo $current_object = $directory.'/'.$object, '<br />';
	   }
	   
	}
}

vose_remove_directory('vose');
?>

When you refresh your page you will see a list of your files and sub directories with the original directory name at the beginning like so:

  • vose/text_1.txt
  • vose/text_2.txt
  • vose/sub_vose

So now we have actually got the real location of this we can go ahead and start to either delete or apply some recursion and apply this function again. Ok, what we want to do is check the current file type of this $object is a directory. Again we are going to use an if statement to process this and we want to say ‘if the filetype of the $current_object is equal to our $directory‘ then delete the directory we are currently in.

Just as a sidestep I can going to code in something here so you can see the file types in your list because its always best to do these things so you know what I am referring to so take a look at this:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      $current_object = $directory.'/'.$object; // notice change in code
		  echo filetype($current_object), '<br />';
	   }
	   
	}
}

vose_remove_directory('vose');
?>

Notice the echo statement line which is going to print on screen the file types for example of the contents of our directory like so:

  • file
  • file
  • dir

As you can see we have our two files and our sub directory within our folder. :) Now we need to create our if statement and we say ‘if filetype of the $current_object is equal to $directory‘ we will need to call the function again and apply that to the current $object. So if its a file we can delete it using our else statement using our unlink() function for our $current_object.

So if the filetype is actually a directory at this stage then we need to apply this entire process again and delete the files within that sub directory and then delete the sub directory itself. Otherwise we would just need to delete unlink() the $current_object like we have done with our else statement. All we need to do is call our function again here for our $current_object and its as simple as that. Take a look:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      $current_object = $directory.'/'.$object;
		  if (filetype($current_object) === $directory) {
		     vose_remove_directory($current_object); // called function again here
		  } else {
		     unlink($current_object);
			 }
	   }
	   
	}
}

vose_remove_directory('vose');
?>

We do have one more line to add which is extremely important but for now as long as you understand how looping through an array of files and creating a recursive function the that’s great. So now what we need to do once we have finished with the last sub directory we want to remove the original directory we first accessed like so:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      $current_object = $directory.'/'.$object;
		  if (filetype($current_object) === 'dir') {
		     vose_remove_directory($current_object); // called function again here
		  } else {
		     unlink($current_object);
			 }
	   }
	   rmdir($directory);
	}
}

vose_remove_directory('vose');
?>

So now we can actually go ahead and test this. I want you to create a folder (directory) called ‘vose_empty’ where you have placed your ‘vose’ directory and your ‘index.php’ file. Change the bottom line of the code to this:

vose_remove_directory('vose_empty');
?>

Then scoot back to your browser and refresh the page. You will see that your newly created ‘vose_empty’ directory has now been removed. Now you can change it back to your ‘vose’ folder name like so:

vose_remove_directory('vose');
?>

Now the code should erase everything in your ‘vose’ folder including our files and sub directories with files and sub directories within them. So when you have changed the code back like above you can go ahead and hit refresh in your browser and you will see by checking your file structure that your ‘vose’ folder has been removed with everything that was inside it.

As you can see this is a very useful function to be able to write although I know understanding the recursion can be quite tricky at times but as long as you can get your head around the fact that we are just basically going down the structure (or the tree) of our files and directories then we are applying the same function to remove sub directories and all its contents.

So my advise would be to just go ahead and place this whole function within a global file that all your website pages can call upon and use this fantastic function anytime you want. So the function at the end looks like this:

<?php
function vose_remove_directory($directory) {
    if (is_dir($directory) === true) {
	   $contents = scandir($directory);
	   unset($contents[0], $contents[1]);
	   
	   foreach($contents as $object) {
	      $current_object = $directory.'/'.$object;
		  if (filetype($current_object) === 'dir') {
		     vose_remove_directory($current_object); // called function again here
		  } else {
		     unlink($current_object);
			 }
	   }
	   rmdir($directory);
	}
}
?>

And we call our function into play using the following code:

<?php
vose_remove_directory('vose');
?>

You can always set your ‘vose’ directory name as a variable don’t forget so you can have your code run dynamically on say such things as folders named after users which no longer exist or products which you no longer sell.

I hope you have enjoyed my ‘Remove Directory Function PHP Snippet’ and if you have any comments please feel free to leave them below.

{lang: ‘en-GB’}


You may also like:

Form Submission – The annoying back button
Random Salt Creator – PHP Snippet – Seasoned Security
Is Android Safe? Up to five million Androids infected – Counterclank
MySQL Table – North American States
PHP Page Counter using txt file – Basic Model

Article Submission

Have you written articles and would like them to appear on shaunellerton.co.uk? If so, then check out my Article Submission section to find out how you can get yourself your very own featured post or even a whole section devoted to your own portfolio.

Submit Article

About the Owner: Shaun Ellerton

Shaun is a man with a background in joinery, music, business, management, web development and computer technologies. A friend and father to a wonderful daughter, he is also a family man.

Read More

3 Responses to A PHP Guide – Delete directory and contents – Walkthrough

  1. A PHP Guide -… http://t.co/BcgRXQYl #aphpguidebyvose #deletedirectoryandcontentsphp #php #PHPGuide #phpwalkthrough #shaunellerton

  2. Hello Jason,

    Thanks for popping back as usual. I enjoyed making this recursive function for some unknown reason. :)

    I am really glad you like it and I really hope you put it in one of your global includes to call upon anytime you need it.

    You are going to have to leave your website link so I can check out your site if you have it finished now. Will have to keep me posted about your progress.

    Best wishes,

    Shaun Ellerton

  3. just totally fantastic walkthrough just so well explained and i think its great how you change the code step by step showing us how things are changing and explaining each step with live examples within your tutorial thanks shaun