Forum Moderators: coopster

Message Too Old, No Replies

how to delete folder

         

jackvull

9:02 am on Jun 15, 2006 (gmt 0)

10+ Year Member



DOes anyone know of a ready made script to delete a folder?
I know you can use rmdir but the manual says the folder has to be empty first so do you have to delete all files with a loop then delete the folder?

What about if the folder has subfolders?

dreamcatcher

9:36 am on Jun 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi jackvull,

Check out the user contributed notes on the PHP.net website for the rmdir() [uk.php.net] function.

This was one posted solution:


function deleteDir($dir)
{
if (substr($dir, strlen($dir)-1, 1)!= '/')
$dir .= '/';
echo $dir;
if ($handle = opendir($dir))
{
while ($obj = readdir($handle))
{
if ($obj!= '.' && $obj!= '..')
{
if (is_dir($dir.$obj))
{
if (!deleteDir($dir.$obj))
return false;
}
elseif (is_file($dir.$obj))
{
if (!unlink($dir.$obj))
return false;
}
}
}
closedir($handle);
if (!@rmdir($dir))
return false;
return true;
}
return false;
}

dc

henry0

11:19 am on Jun 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I found in the manual a user contrib that I use and works great
BEWARE OF THE PATH as you know this a one way ticket!
<<<
<?php

// function rm()

/** // PHP Manual - credit to ****bishop****
* rm() -- Vigorously erase files and directories.
*
* @param $fileglob mixed If string, must be a file name (foo.txt), glob pattern (*.txt), or directory name.
* If array, must be an array of file names, glob patterns, or directories.
*/
function rm($fileglob)
{
if (is_string($fileglob)) {
if (is_file($fileglob)) {
return unlink($fileglob);
} else if (is_dir($fileglob)) {
$ok = rm("$fileglob/*");
if (! $ok) {
return false;
}
return rmdir($fileglob);
} else {
$matching = glob($fileglob);
if ($matching === false) {
trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
return false;
}
$rcs = array_map('rm', $matching);
if (in_array(false, $rcs)) {
return false;
}
}
} else if (is_array($fileglob)) {
$rcs = array_map('rm', $fileglob);
if (in_array(false, $rcs)) {
return false;
}
} else {
trigger_error('Param #1 must be filename or glob pattern, or array of filenames or glob patterns', E_USER_ERROR);
return false;
}

return true;
}
?>

>>>