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);
    }
}

4 thoughts on “PHP: Recursively create directories

  1. Will Anderson (August 22, 2011)

    According to the documentation page for mkdir (http://www.php.net/manual/en/function.mkdir.php), there’s a $recursive parameter you can use to provide the same functionality. It’s probably faster to use the core implementation rather than implement your own, right?

    1. blobaugh (August 22, 2011)

      Don’t make me hurt you!

  2. Emo (January 22, 2013)

    Will, the documentation says the $recursive parameter is available since php 5. Thank you Ben for this post.

  3. Batam (September 24, 2015)

    I am very new in php scripting.. you save my day…

    Thank you for the script..

    regards,

    Batam