How to create a folder in PHP if it doesn’t exist

This article will show you how to create a folder automatically in PHP if it does not exist.  We will see several different approaches to solve this problem in a right way.

Creating a new folder in PHP

The most simple solution would be first just to ask if the folder exists. If the folder does not exist then we can create it. It already exists, then we shall do nothing.

Here is a simple example for the custom makeDirectory() function:

<?php

function makeDirectory($new_path, $mode) {
    if (!file_exists($new_path)) {
        mkdir($new_path, $mode, true);
        echo "New folder was created.<br>";
    }
}

$new_path = 'my_project/new/directory';
$mode = 0777;

makeDirectory($new_path, $mode); //New folder was created.

Let’s stop here for a while and explain a little bit used terms. The PHP mkdir() function will create a new directory. Its method signature according to the official PHP documentation [link] is like this:

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

As we can see only the first parameter $pathname is mandatory. The second parameter $mode is by default set to 0777. It represents chmod settings for the folder. For now, we only need to know that this number represents various folder access rights in operating systems.

If you want to know more about chmod , check codepills.com about more chmod articles.

The reason why we used second parameter chmod is the fact we wanted to use the third method parameter $recursive. It allows the creation of nested directories specified in the $pathname.

This code will secure creation of folder on arbitrary path declared in the $pathname string from the root file in which the function was executed.

If you want to create a folder just in your root directory, you can write instead of the path just a name of the folder.

Creating a new folder in PHP in a defensive way

A much clever and concise solution against the one we have seen is to use is_dir() instead of file_exists()file_exists()  is method asking if file or directory exists.  is_dir()  is optimized just for directories and therefore even faster.

Moreover, we should be sure that requested path does not already exist before even asking the mkdir() function to do anything. Instead of if-else conditional loggic, we can do boolean logic straight on the return.

<?php

function makeDirectory($new_path, $mode) {
    return is_dir($new_path) || mkdir($new_path, $mode, true);
}

$new_path = 'my_project/new/directory';
$mode = 0777;

makeDirectory($new_path, $mode);

This does not work if there is aleardy a filename with same name.

This will recursively create directory path with much less code. We are using the power of OR operator. If the first expression is evaluated as true, it means that the folder exists. In OR operation first, true evaluation is the reason to stop evaluation and do not continue further.

However, if the first expression is evaluated as false, then OR will ask the second expression for evaluation. Now we know that the folder does not exist and therefore if themkdir() function creates the folder without error, it will return true. This means that the new folder was created.

<?php

function makeDirectory($new_path, $mode) {
    $return = mkdir($new_path, $mode, true);
    return $return === true || is_dir($new_path);
}

$new_path = 'my_project/./directory';
$mode = 0777;

$result = makeDirectory($new_path, $mode);
echo($result);

If we are sure that the directory we want to create will not exist, we can just slightly change our custom function and make it in the same way effective.

But be aware of forbidden characters. Each operating system has some special characters which can not be used for the directory name. For example, Windows operating systems denies using /?<>\:*|" , Mac systems deny using dot in the folder name.

This entry was posted in PHP. Bookmark the permalink.

1 Response to How to create a folder in PHP if it doesn’t exist

  1. Pingback: How to create file in different directory in PHP | Codepills.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.