php 如果文件夹不存在,则创建一个文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2303372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:56:41  来源:igfitidea点击:

Create a folder if it doesn't already exist

phpwordpressdirectory

提问by Scott B

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

我遇到了一些使用Bluehost安装 WordPress 的情况,在这些情况下,我遇到了 WordPress 主题错误,因为上传文件夹wp-content/uploads不存在。

Apparently the Bluehost cPanelWordPress installer does not create this folder, though HostGatordoes.

显然 Bluehost cPanelWordPress 安装程序不会创建此文件夹,但HostGator会创建。

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

所以我需要向我的主题添加代码来检查文件夹并以其他方式创建它。

回答by Gumbo

Try this:

尝试这个:

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

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

请注意,这0777已经是目录的默认模式,并且仍可能被当前的 umask 修改。

回答by Satish Gadhave

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

这是缺失的部分。您需要在 mkdir 调用中将“递归”标志作为第三个参数(布尔值为真)传递,如下所示:

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

回答by phazei

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.

可以通过提供停止级别来改进,因此如果它超出用户文件夹或其他内容并包含权限,它就会失败。

回答by AndiDog

What about a helper function like this:

像这样的辅助函数怎么样:

function makeDir($path)
{
     $ret = mkdir($path); // use @mkdir if you want to suppress warnings/errors
     return $ret === true || is_dir($path);
}

It will return trueif the directory was successfully created or already exists, and falseif the directory couldn't be created.

true如果目录创建成功或已经存在,以及false目录无法创建,它将返回。

A betteralternative is this (shouldn't give any warnings):

一个更好的选择是这样的(不应该给出任何警告):

function makeDir($path)
{
     return is_dir($path) || mkdir($path);
}

回答by Elyor

Faster way to create folder:

创建文件夹的更快方法:

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

回答by user

Recursively create directory path:

递归创建目录路径:

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

Inspired by Python's os.makedirs()

受 Python 的启发 os.makedirs()

回答by Trevor Mills

Within WordPress there's also the very handy function wp_mkdir_pwhich will recursively create a directory structure.

在 WordPress 中还有一个非常方便的函数wp_mkdir_p,它将递归地创建一个目录结构。

Source for reference:-

参考来源:-

function wp_mkdir_p( $target ) {
    $wrapper = null;

    // strip the protocol
    if( wp_is_stream( $target ) ) {
        list( $wrapper, $target ) = explode( '://', $target, 2 );
    }

    // from php.net/mkdir user contributed notes
    $target = str_replace( '//', '/', $target );

    // put the wrapper back on the target
    if( $wrapper !== null ) {
        $target = $wrapper . '://' . $target;
    }

    // safe mode fails with a trailing slash under certain PHP versions.
    $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
    if ( empty($target) )
        $target = '/';

    if ( file_exists( $target ) )
        return @is_dir( $target );

    // We need to find the permissions of the parent folder that exists and inherit that.
    $target_parent = dirname( $target );
    while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
        $target_parent = dirname( $target_parent );
    }

    // Get the permission bits.
    if ( $stat = @stat( $target_parent ) ) {
        $dir_perms = $stat['mode'] & 0007777;
    } else {
        $dir_perms = 0777;
    }

    if ( @mkdir( $target, $dir_perms, true ) ) {

        // If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
        if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
            $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
            for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
                @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
            }
        }

        return true;
    }

    return false;
}

回答by Progrower

I need the same thing for a login site. I needed to create a directory with a two variables. The $directory is the main folder where I wanted to create another sub-folder with the users license number.

对于登录站点,我需要同样的东西。我需要创建一个包含两个变量的目录。$directory 是我想用用户许可证号创建另一个子文件夹的主文件夹。

include_once("../include/session.php");
$lnum = $session->lnum; //Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in

if (!file_exists($directory."/".$lnum)) {
mkdir($directory."/".$lnum, 0777, true);
}

回答by Andreas

This is the most up-to-date solution without error suppression:

这是没有错误抑制的最新解决方案:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory');
}

回答by joaorodr84

If you want to avoid the file_existsVS is_dirproblem, I would suggest you to look here

如果你想避免file_existsVSis_dir问题,我建议你看这里

I tried this and it only creates the directory if the directory does not exist. It does not care it there is a file with that name.

我试过这个,它只在目录不存在时创建目录。它不在乎是否有一个具有该名称的文件。

/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
    mkdir($path_to_directory, 0777, true);
}