adrianTNT Posted November 1, 2008 Share Posted November 1, 2008 Hello, I have a function that is supposed to loop over a given directory and remove all its sub files AND folders. The problem is... in some situations it crashes the server, I think it does an infinite loop. I know that it does this when I have MAC files in that folder, whenever this happens I always have a sub folder named "__MACOSX" and inside that folder there are files starting with "._", like ._photo.jpg Can someone please tell me how to fix ths function? It probably has something to do with area $child[0] == '.' Or maybe cause is that directory is never closed back, I dont know where to close it (not my code) // remove all contents of the directory function rmdir_r($path) { if (!is_dir($path)) {return false;} $stack = Array($path); while ($dir = array_pop($stack)) { if (@rmdir($dir)) {continue;} $stack[] = $dir; $dh = opendir($dir); while (($child = readdir($dh)) !== false) { if ($child[0] == '.') {continue;} $child = $dir . DIRECTORY_SEPARATOR . $child; if (is_dir($child)) {$stack[] = $child;} else {unlink($child);} } } return true; } rmdir_r('temp2'); Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/130951-infinite-loop-when-trying-to-remove-a-directory-and-its-contents/ Share on other sites More sharing options...
genericnumber1 Posted November 1, 2008 Share Posted November 1, 2008 It would be easier to use a recursive function... <?php function delete_contents($dir) { if($dir[strlen($dir)-1] != DIRECTORY_SEPARATOR) { $dir .= DIRECTORY_SEPARATOR; } if(is_dir($dir)) { $dh = opendir($dir); while(($file = readdir($dh)) !== false && $file != '.' && $file !='..') { if(is_dir($file)) { delete_contents($dir . $file); } else { unlink($dir . $file); } } rmdir($dir); } } ?> and it would be MUCH easier to use scandir() instead of opendir(), though it's less memory efficient. Or you could use the directory iterator class, but I'll spare you that method. this code is untested, so I'd suggest testing/fixing any bugs first, and I used the DIRECTORY_SEPARATOR constant since your original code did. Quote Link to comment https://forums.phpfreaks.com/topic/130951-infinite-loop-when-trying-to-remove-a-directory-and-its-contents/#findComment-679860 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.