Jump to content

delete all files in a directory and then delete the directory


lindylex

Recommended Posts

This is a simple delete all files in a directory and then delete the directory but it does not work.  Does any one have an idea?

 


function del_this_directory ($directory_to_del){

foreach (new DirectoryIterator ($directory_to_del) as $file){
	if (!is_dir ($file)){
		unlink ($file ->getPathname ());
	}

}
//This will remove the directory
rmdir($directory_to_del);
}	
del_this_directory ("../del/");

 

This will delete the directory if I do this without obviously no file(s) within the directory.

 


function del_this_directory ($directory_to_del){

/*
foreach (new DirectoryIterator ($directory_to_del) as $file){
	if (!is_dir ($file)){
		unlink ($file ->getPathname ());
	}

}
*/	
        //This will remove the directory
rmdir($directory_to_del);
}	
del_this_directory ("../del/");

 

I think something here "foreach (new DirectoryIterator ($directory_to_del) as $file){" is keeping the directory open.  An not letting me delete the empty directory.

 

Just to let you know the permission for this directory is 0777 so that's not the problem.

 

Thanks

try this

(its not mine but works well)

<?php
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}

//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.