PHP Create Directory If It Doesn't Exist Example

By Hardik Savani July 30, 2020 Category : PHP

In this tutorial we will go over the demonstration of php create folder if not exist. you can understand a concept of php create directory if not exists. we will help you to give example of php code to create directory if not exists. This article goes in detailed on create directory if not exist php. So, let's follow few step to create example of php make directory if not exist.

Sometime, we need to create directory from php code. for example if you are storing images on folder wire then you don't have to go on server and create you must have to write code to create dynamically folder using php code.

So, here i will give you very simple example of how to create folder if does not exist.

Example 1

In this example, we will use is_dir() and mkdir() to create directory if does not exist. is_dir() will help to check if folder is exit or not and mkdir() will help to create new folder.

Code:

<?php

$directoryName = 'images';

/* Check if the directory already exists. */

if(!is_dir($directoryName)){

/* Directory does not exist, so lets create it. */

mkdir($directoryName, 0755);

}

?>

Example 2

Sometime, we need to create nested directories specified in the pathname. so in this example, i will give you how you can do it in php.

mkdir() function has third argument that allow to creating nested folder. you have to pass TRUE.

Let's see bellow example:

Code:

<?php

$directoryName = 'images/1/thumb';

/* Check if the directory already exists. */

if(!is_dir($directoryName)){

/* Directory does not exist, so lets create it. */

mkdir($directoryName, 0755, true);

}

?>

I hope it can help you...

Tags :