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条回答
爷、活的狠高调
2楼-- · 2019-01-04 15:57
if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-04 16:03

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

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;
}
查看更多
地球回转人心会变
4楼-- · 2019-01-04 16:04

To create a folder if it doesn't already exist

Considering the question's environment.

  • WordPress.
  • Webhosting Server.
  • Assuming its Linux not Windows running PHP.

And quoting from: http://php.net/manual/en/function.mkdir.php

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )

Manual says that the only required parameter is the $pathname!

so, We can simply code:

<?php
error_reporting(0); 
if(!mkdir('wp-content/uploads')){
   // todo
}
?>

Explanation:

We don't have to pass any parameter or check if folder exists or even pass mode parameter unless needed; for the following reasons:

  • The command will create the folder with 0755 permission (Shared hosting folder's default permission) or 0777 the command's default.
  • mode is ignored on Windows Hosting running PHP.
  • Already the mkdir command has build in checker if folder exists; so we need to check the return only True|False ; and its not an error, its a warning only, and Warning is disabled in hosting servers by default.
  • As per speed, this is faster if warning disabled.

This is just another way to look into the question and not claiming a better or most optimal solution.

Tested on PHP7, Production Server, Linux

查看更多
Evening l夕情丶
5楼-- · 2019-01-04 16:06

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

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory');
}
查看更多
We Are One
6楼-- · 2019-01-04 16:07

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.

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);
}
查看更多
别忘想泡老子
7楼-- · 2019-01-04 16:09

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 true if the directory was successfully created or already exists, and false if the directory couldn't be created.

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

function makeDir($path)
{
     return is_dir($path) || mkdir($path);
}
查看更多
登录 后发表回答