Full of lovely web standards information and a large helping of PHP

PHP recursive directory remove function

10 months, 28 days ago

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.

  1. <?php
  2. function RemoveDir($sDir) {
  3. if (is_dir($sDir)) {
  4. $sDir = rtrim($sDir, '/');
  5. $oDir = dir($sDir);
  6. while (($sFile = $oDir->read()) !== false) {
  7. if ($sFile != '.' && $sFile != '..') {
  8. (!is_link("$sDir/$sFile") && is_dir("$sDir/$sFile")) ? RemoveDir("$sDir/$sFile") : unlink("$sDir/$sFile");
  9. }
  10. }
  11. $oDir->close();
  12. rmdir($sDir);
  13. return true;
  14. }
  15. return false;
  16. }
  17. ?>

Comments

  • I'd be interested to know if this is faster than something like:

    $res = `rm -fr $dir`;

    Though presumably a php function avoids the safe mode restriction.

    Stuart Colville - 27th September 2007

  • > 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())

    is_link - 27th September 2007

  • > $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 - 27th September 2007

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

    Ed Eliot - 27th September 2007

Help make this post better

Notes: Standard BBCode for links, bold, italic and code are supported. rel="nofollow" is added to all links. Your email address will never be displayed on the site.

Back to index