Create a directory if it does not exists in PHP

By Faruque Ahamed Mollick

Creating a directory in PHP is so easy. In just one line of code, we can make a directory. The PHP function that used to make a directory isĀ mkdir().

Suppose, we want to make a directory with the directory name “my_directory” using the PHP mkdir() function. below is the code that can do that:

How to detect the file extension in PHP?



Listing files from directory that have particular extensions in PHP

mkdir("my_directory");

But what happened if the directory with the name “my_directory” already exists?

If the directory already exists with the name and we are going to create a directory with the same name then it will show the PHP warning message. So before we make our directory, we must have to check if the directory exists or not.

Below is the code where we are checking if the directory exists or not before creating the new one:

<?php

//Name of our directory
$dir_name ='my_directory';

//Check if the directory with the name already exists
if (!is_dir($dir_name)) {
//Create our directory if it does not exist
mkdir($dir_name);
echo "Directory created";
}

?>

In the above code first, we have check if the directory already exists or not. We have used is_dir() PHP function to check if the directory exists or not. If the is_dir function returns boolean FALSE, then it means the directory does not exist and it will run the mkdir() function and the directory will be created.

That’s it. We have successfully created our directory after checking if it exists or not.

Display the country flag of visitors in PHP

Leave a Reply

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