ItSolutionStuff.com

PHP Create Directory If It Doesn't Exist Example

By Hardik Savani • May 14, 2024
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: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

PHP - Dropzone Add Download Button Example

Read Now →

Laravel Copy File from One Folder to Another Example

Read Now →

Laravel Check If Folder Exists Before Create Directory Example

Read Now →

How to Remove Duplicate Values from Array in PHP?

Read Now →

How to Get Folder Path from File Path in PHP?

Read Now →

PHP Check Word Exist in String or Not Example

Read Now →

How to Get the File Size in PHP?

Read Now →

How to Convert Array Values to Lowercase in PHP?

Read Now →

How to Convert Object into Array in PHP?

Read Now →

How to Get Minimum Key Value of Array in PHP?

Read Now →

How to Count Number of Files in a Directory in PHP?

Read Now →