A working recursive directory remove function for PHP
I’ve got a client that really wanted to have functionality built into his site that would duplicate a directory and all the files. No big deal except that all the files end up owned by nobody and with the permissions set to 644, which means I can’t delete them via FTP when something goes wrong or they duplicate too many times. I’ve looked in the past for a PHP script that would remove these extra directories without finding anything that would actually help. I circled back on the problem this week and found a great script that actually does a recursive directory delete and was able to remove these annoying folders.
I didn’t write this, but I am going to include the code here in case the original source ever goes offline.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function 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; } |
Source: Ed Eliot
25 Sep 2009 07:18 am Chris 0 comments