How to delete folder with contents in it in PHP

Many times in PHP, we need to delete the folder containing subfolders and files. So we have to check for depth and according to that we have to delete files first and then folders. But if we don’t know the content of it then it will be very difficult task to delete it. I am working on some stuff that need to be delete once it is utilized so I make the function that check for the subfolders and files and recursively delete the contents of it.

Here is the function for delete.

function delFolder($folder) 
{ 
	foreach(glob($folder . '/*') as $file) 
	{ 
		if(is_dir($file)) 
			delFolder($file); 
		else 
			unlink($file); 
	} 
	rmdir($folder); 
}

Here delFolder is the function that perform delete task.

Here we use following of the PHP function.

  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • unlink — Deletes a file
  • rmdir — Removes directory

Download the full example with comments here : https://www.mediafire.com/view/winyqdt2fr1jsll/delFolder.php

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s