PHP Create Directory If It Doesn't Exist Tutorial

PHP 8 , PHP

Nicesnippets

484

16-04-2021


PHP Create Directory If It Doesn't Exist Tutorial

Hi Guys,

Today,I will learn you how to create directory if it doesn't exist useing php. we will show example of php create directory if it doesn't 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.

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

Example 1


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

<?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

In thi step,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.

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

}

?>

It will help you....