PHP: Recursively create directories

August 22, 2011

The mkdir function in PHP is great for creating directories, but what if you need to create a new directory structure? For example, you run mkdir(“/this/is/a/path”) but only “/this” exists. mkdir will fail because /this/is/ does not exist. The way to solve this is to pull the path apart and check each segment to ensure that it exists and create it if it does not exist.I created a recursive mkdir function and would like to share it with you. To get this to work simply copy the function into your code and call rmkdir instead of PHP’s mkdir.

function rmkdir($path) {
    $path = str_replace("\\", "/", $path);
    $path = explode("/", $path);
    
    $rebuild = '';
    foreach($path AS $p) {
        
        if(strstr($p, ":") != false) { 
            echo "\nFound : in $p\n";
            $rebuild = $p;
            continue;
        }
        $rebuild .= "/$p";
        echo "Checking: $rebuild\n";
        if(!is_dir($rebuild)) mkdir($rebuild);
    }
}