Create a folder if it doesn't already exist Create a folder if it doesn't already exist wordpress wordpress

Create a folder if it doesn't already exist


Try this, using mkdir:

if (!file_exists('path/to/directory')) {    mkdir('path/to/directory', 0777, true);}

Note that 0777 is already the default mode for directories and may still be modified by the current umask.


Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:

mkdir('path/to/directory', 0755, true);


Something a bit more universal since this comes up on google. While the details are more specific, the title of this question is more universal.

/**  * recursively create a long directory path */function createPath($path) {    if (is_dir($path)) return true;    $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );    $return = createPath($prev_path);    return ($return && is_writable($prev_path)) ? mkdir($path) : false;}

This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.

Could be improved by providing a stopping level so it just fails if it goes beyond user folder or something and by including permissions.