Here's a function for removing a directory and all subdirectories and files. I knocked this together as part of a tool I'm currently writing but then realised I didn't need it. It's pretty simple and I know one can find similar code elsewhere but rather than simply throwing it away I thought I'd post it here in case it's useful to anyone.
<?phpfunction RemoveDir($sDir) {if (is_dir($sDir)) {$sDir = rtrim($sDir, '/');$oDir = dir($sDir);while (($sFile = $oDir->read()) !== false) {if ($sFile != '.' && $sFile != '..') {(!is_link("$sDir/$sFile") && is_dir("$sDir/$sFile")) ? RemoveDir("$sDir/$sFile") : unlink("$sDir/$sFile");}}$oDir->close();rmdir($sDir);return true;}return false;}?>
I'd be interested to know if this is faster than something like:
Though presumably a php function avoids the safe mode restriction.
> is_dir("$sDir/$sFile") ? RemoveDir("$sDir/$sFile")
if $sDir/$sFile here is a symlink pointing to a directory, your function will try to do a rmdir on a symlink (after having removed the contents of the pointed directory !). It will fail, and then removing parent directory will fail too ;) You should use (!is_link()&&is_dir())
> $res = `rm -fr $dir`;
You should use escapeshellarg() on $dir (what if $dir == "somedir && rm -rf /" ? ;) )
You should put the "--" argument before $dir, to avoid problems if your $dir starts with a "-"
You should use system() or any other function which will give you the return status of the command
is_link - Good spot, thanks. I'll add the is_link() check.
With regards to Stuart's comment in the context in which we were discussing this $dir doesn't come from user input and it wouldn't therefore have been possible to inject additonal commands but your totally right that in principle one should use escapeshellarg() in situations where it could be a problem.