Recursive delete folder in php

Reading time ~1 minute

This problem came up where I needed to remove a folder. Removing a folder is easy, only the PHP command rmdir() only removes the folder if it is empty. The PHP command unlink() is only for files.

So how do I recursively delete a folder that might not be empty? Here is a function for you:

<?
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
 
Then just call it with the non-empty folder you want to remove.

<?
rrmdir('folderName');

Quick Laravel/Lumen install with Docker!

The default installer that comes with Laravel is great, but unfortunately that means you have to install dependencies of PHP and Laravel/...… Continue reading

PHP To Python

Published on February 24, 2016

Aftertouch in Logic Pro X and 2015 Macbook Pro

Published on February 24, 2016