Create a folder if it doesn't already exist

2019-01-04 15:44发布

I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.

Apparently the Bluehost cPanel WP installer does not create this folder, though HostGator does.

So I need to add code to my theme that checks for the folder and creates it otherwise.

13条回答
Root(大扎)
2楼-- · 2019-01-04 15:46

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.

查看更多
相关推荐>>
3楼-- · 2019-01-04 15:46

Faster way to create folder:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}
查看更多
叛逆
4楼-- · 2019-01-04 15:54

Try this:

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.

查看更多
相关推荐>>
5楼-- · 2019-01-04 15:54
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
   mkdir( $upload_dir, 0700 );
}
查看更多
ら.Afraid
6楼-- · 2019-01-04 15:55

Recursively create directory path:

function makedirs($dirpath, $mode=0777) {
    return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}

Inspired by Python's os.makedirs()

查看更多
孤傲高冷的网名
7楼-- · 2019-01-04 15:56

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);
查看更多
登录 后发表回答