Create a folder if it doesn't already exist

Viewed 802051

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.

21 Answers

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.

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

The best way is to use the wp_mkdir_p function. This function will recursively create a folder with the correct permissions.

Also, you can skip folder exists condition because the function returns:

  • true when the directory was created or existed before
  • false if you can't create the directory.

Example:

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

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

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.

There is another WordPress function named wp_upload_dir(). It returns the upload directory path and creates a folder if doesn't already exists.

$upload_path = wp_upload_dir();

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

To create a folder if it doesn't already exist

Considering the question's environment.

  • WordPress.
  • Webhosting server.
  • Assuming it's Linux, not Windows running PHP.

And quoting from: mkdir

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

The 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 the folder exists or even pass the mode parameter unless needed; for the following reasons:

  • The command will create the folder with 0755 permission (the 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 a built-in checker for if the folder exists; so we need to check the return only True|False ; and it’s not an error; it’s a warning only, and Warning is disabled on the 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.

It was tested on PHP 7, production server, and Linux

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

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

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

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

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.

We can create folder using mkdir. Also we can set permission for it.

Value Permission
0     cannot read, write or execute
1     can only execute
2     can only write
3     can write and execute
4     can only read
5     can read and execute
6     can read and write
7     can read, write and execute
<?PHP
  
// Making a directory with the provision
// of all permissions to the owner and 
// the owner's user group
mkdir("/documents/post/", 0770, true)
  
?>

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