Jump to content

Infinite loop (when trying to remove a directory and its contents)


Recommended Posts

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.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.