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 the right way.

Creating a new folder in PHP

The most straightforward solution would be first to ask if the folder exists. If the folder does not exist, then we can create it. However, if 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 snippeds of code. 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 default chmod settings for the newly created 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 the second parameter chmod is because we wanted to use the third method parameter $recursive. It allows the creation of nested directories, subdirectories, specified in the $pathname.

This code will secure creating a folder on an arbitrary path declared in the $pathname string from the root file where the called function is executed.

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

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() snippet. file_exists() is method asking if the file or directory exists. is_dir() is optimized just for directories and therefore even faster.

Moreover, we should be sure that the requested path does not already exist before even asking the mkdir() function to do anything. Instead of if-else conditional logic, 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);

The code snippet above does not work if there is already a filename with the same name. Otherwise, the code snippet will recursively create a directory path with much less code.

We are using the power of the OR operator. If the first expression is evaluated as true, it means that the folder exists. In OR operator first true evaluation is the reason to stop evaluating whole expression and evaluation do not continue further. It computer science this property of OR operator is better known as short circuit.

However, if the first expression is evaluated as false, OR will ask the second half of the expression for evaluation. Now we know that the folder does not exist, and therefore mkdir() method is called. If themkdir() function creates the folder without error, it will return true. Therefore, in the end, we get confirmation that the new folder exists.

<?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 slightly change our custom function and make it in the same way more 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 /?<>\:*|" , Unix based systems deny using dot in the folder name.

Conclusion

This article has shown how to create a folder automatically in PHP if it does not exist. We have demonstrated several different approaches to solve this problem in the right way.

This entry was posted in Tutorials and tagged , . Bookmark the permalink.

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