Hardware, Software, Firmware, and Everything

Recursively Clear Directory with PHP

I was working on a PHP program that reads  zipped files, extracts wanted files, stores the contents in a MySql database, and finally cleans up the contents of a local tmp directory.  I develop and debug the program on a local LAMP server, then upload and test it on a public web server.  I thought it was all finished, when I noticed that the public server printed out some PHP warnings that it was trying to unlink a directory, rather than a file.    I had forgotten that the tmp dir included sub-directories.

I could change the tmp directory structure, but that would involve many edits, and I decided to just fix my clear_tempdir() function.  It turned out to be a 2 line fix, which added a recursive call to itself.

function clear_tempdir($dir) {
  $dh = opendir($dir);
  while ($file = readdir($dh)) {
    if( "." == $file || ".." == $file ){
      continue; // avoids deleting . and .. (probably same as is_dir())
    } elseif(is_dir($dir.'/'.$file)) {  // two lines added to avoid trying to delete sub-directories
      clear_tempdir($dir.'/'.$file); // recursion!
    } else {
      unlink($dir.'/'.$file);  // delete the file

I’m sure there are other examples out there, but this one came to me as a quick fix and with 2 lines of code, it couldn’t have been much quicker.

For the curious, the project is here.  It is part of an enhancement to my jata Android app.  Note that it is intended as a back end, so is not really production quality UX.


Freelancer dot com – It’s all about (their) money


Use wget to debug remote XML feeds using XmlPullParser


  1. Kris Karas

    Don’t forget the closedir() to avoid a memory leak.
    Or, you could use scandir() too, something like:

    function nukedir ($dir) {
    if ($dir == “.” || $dir == “..”) return;
    foreach (scandir($dir) as $entry) {
    if (is_dir($path = $dir.”/”.$entry)) nukedir($path);
    else unlink($path);

    • Kris, it is refreshing to have a comment that’s actually on topic and not from a spammer using wordpress sites as free link advertising.
      Thanks for the closedir() tip. http://nl3.php.net/function.closedir confirms this. This points out why you make money doing this, while I’m just struggling along.
      I’ll add the fix. I use Eclipse Juno, and I have it in Android Java mode now, I’ll need to re-open in Web mode. I imagine you use vi for all your code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress & Theme by Anders Norén