Marius van Witzenburg We fight for our survival, we fight!

2jul/110

How to recursive delete files and directories with PHP

Posted by mariusvw

This is an example how you could recursive delete directories with PHP.

Keep in mind that you ALWAYS define a root where this function should do its action.

This can seriously remove all your files.

define('UPLOADFILES', dirname(dirname(__FILE__)) . '/uploadfiles');
 
function recursiveDelete($path) {
	if (strpos($path, UPLOADFILES) === false) {
		exit('Trying to remove from wrong path to uploadfiles!');
	}
	if (is_file($path)) {
		return unlink($path);
	} elseif ( is_dir($path) ){
		$objects = scandir($path);
		foreach ($objects as $object) {
			if($object != '.' && $object != '..'){
				recursiveDelete($path . '/' . $object);
			}
		}
		reset($objects);
		return rmdir($path);
	}
}