[php] Create a folder if it doesn't already exist

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 WordPress 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.

This question is related to php wordpress directory

The answer is


As a complement to current solutions, a utility function.

function createDir($path, $mode = 0777, $recursive = true) {
  if(file_exists($path)) return true;
  return mkdir($path, $mode, $recursive);
}

createDir('path/to/directory');

It returns true if already exists or successfully created. Else it returns false.


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

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

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.


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);

If you want to avoid the file_exists VS is_dir problem, I would suggest you to look here

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);
}

if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}

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;
}

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


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);
}

$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
   mkdir( $upload_dir, 0700 );
}

Recursively create directory path:

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

Inspired by Python's os.makedirs()


Faster way to create folder:

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

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);
}

You can try also:

$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);

Better to use wp_mkdir_p function for it. This function will recursively create a folder with the correct permissions. Also, you can skip folder exists condition because it will be check before creating.

$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
    // Directory exists or was created.
}

More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/


You first need to check if directory exists file_exists('path_to_directory')

Then use mkdir(path_to_directory) to create a directory

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

More about mkdir() here

Full code here:

$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
    mkdir($structure);
}

For your specific question about WordPress, use the following code:

if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');

Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.

The following code is for PHP in general.

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

Function reference: PHP is_dir()


We should always modularise our code and I've written the same check it below... We first check the directory, if the directory is absent we create the directory.

$boolDirPresents = $this->CheckDir($DirectoryName);

if (!$boolDirPresents) {
        $boolCreateDirectory = $this->CreateDirectory($DirectoryName);
        if ($boolCreateDirectory) {
        echo "Created successfully";
      }
  }

function CheckDir($DirName) {
    if (file_exists($DirName)) {
        echo "Dir Exists<br>";
        return true;
    } else {
        echo "Dir Not Absent<br>";
        return false;
    }
}

function CreateDirectory($DirName) {
    if (mkdir($DirName, 0777)) {
        return true;
    } else {
        return false;
    }
}

Here you go.

if (!is_dir('path/to/directory')) {
    if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
        throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to wordpress

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ How to get WooCommerce order details Wordpress plugin install: Could not create directory WooCommerce: Finding the products in database How to get post slug from post in WordPress? How to get featured image of a product in woocommerce Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610 Use .htaccess to redirect HTTP to HTTPs Load More Posts Ajax Button in WordPress How to decode encrypted wordpress admin password?

Examples related to directory

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit)