Contact!

Recursively make directories in PHP using mkdir

Recursively make directories in PHP using mkdir

Quite often you will need to create or edit files in a PHP application. The problem is that you will probably need to create the directory structure at some stage. Therefore, it is useful to know how to recursively make directories easily.

To do this we are first going to check whether the current directory structure exists. If it doesn’t, we are going to recursively create all the folders using mkdir(). You might have guessed, but the purpose of this function is creating directory paths. You can directly create a directory or recusively create the directory structure by passing a boolean flag.

We’ll start with a function, and pass it a path variable. This will serve as our base:

function makeDirPath($path) {

}

Check whether the current directory exists

We can check whether a directory exists using either file_exists() or is_dir(). The thing is, is_dir() is actually telling us whether the given path/file is a directory, and therefore it returns false if the directory doesn’t exist. file_exists() checks whether the file or directory exists, and as we are checking whether a directory exists I strongly suggest we use it.

function makeDirPath($path) {
    return file_exists($path);
}

Note: We are checking whether the file exists first to avoid errors later.

Recursively make directories if they don’t exist

Our function is currently pretty useless. It returns true or false depending on whether a directory exists or not. The next step is to use mkdir() when file_exists() returns false.

To do this we are going to use an or (||) operator:

function makeDirPath($path) {
    return file_exists($path) || mkdir($path, 0777, true);
}

We are passing mkdir the path, the file permissions (0777 is default, and it is ignored in windows), and setting the recursive flag to ‘true’. If the file doesn’t exist, the entire directory structure will be recursively created.

Drop the function into your project and call it whenever you need a new directory.

  1. Anon says:

    How is this article written on 05/03/2021 when today in only 03/16/2021 ?????

    1. Eric says:

      because : DD/MM/YYYY

      1. Seba says:

        Nope, he’s come from the future 😎 haha

        1. Seba says:

          He comes from* Sorry, my english is not pretty good 🙁

Join the discussion!

You might like: