Re: Function Get Error
| From: | Torsten Roehr | Date: | Fri, 03 Sep 2004 09:00:23 +0000 |
| Subject: | Re: Function Get Error | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-195702@lists.php.net to get a copy of this message | ||
>"Difenza2003@Libero.It" <difenza2003@libero.it> wrote in message
news:I3GGLA$2EF19136EDB245A0FD6391F4BBD3994A@libero.it...
>
>I write this function to delete directory and file but when i 've a
directory not empty i get error
>The code that i write is this:
>
>I receive this warning:
>Warning: rmdir(cartella): Directory not empty in c:\programmi\apache
group\apache\users\test\project\delete.php on line 23
>I have set chmod on linux chmod to 777 but i can delete folder only when is
empty.
>What I do ?
>Thanks to all and sorry for my bad language.
I guess you'll first have to delete all files in the directory. Try this
function:
/**
* Recursively clear a local directory
*
* @param string $sourceDir directory to delete
* @param integer $level directory level (to avoid deleting the
root dir)
*/
function clearDirectory($sourceDir, $level = 0)
{
// proceed if source directory exists
if (is_dir($sourceDir))
{
// read dir contents
if ($handle = opendir($sourceDir))
{
/* This is the correct way to loop over the
directory. */
while(false !== ($dirItem = readdir($handle)))
{
if ($dirItem != '.' && $dirItem !=
'..')
{
// directory
if (is_dir($sourceDir . '/'
. $dirItem))
{
clearDirectory($sourceDir . '/' . $dirItem, $level + 1);
}
// file
elseif (file_exists($sourceDir
. '/' . $dirItem))
{
unlink($sourceDir .
'/' . $dirItem);
}
}
}
// remove directory if it's not the root one
if ($level > 0)
{
rmdir($sourceDir);
}
}
closedir($handle);
}
}
It will delete all direcotries and files *inside* the specified directory.
So the directory itself will not be deleted.
Just call it like this (without trailing shlash!!!):
clearDirectory('/path/to/directory');
Hope it works for you.
Regards, Torsten Roehr