Create a directory if it doesn’t already exist in PHP
This article demonstrates how to create a directory if it doesn’t already exist in PHP.
In PHP, you can use the mkdir() function to create the specified directory. It returns true on success and false on failure. However, if the directory already exists, mkdir() will return false. Therefore, it is recommended to check for the existence of the directory before trying to create it. This can be done using the file_exists() function.
|
1 2 3 4 5 6 7 |
<?php $dir = '/path/to/directory/'; if (!file_exists($dir)) { mkdir($dir); } ?> |
You may want to set the recursive parameter to true, which additionally creates any parent directories of the specified directory. All directories are created with the specified permission, which is 0777 by default.
|
1 2 3 4 5 6 7 |
<?php $dir = '/path/to/directory/'; if (!file_exists($dir)) { mkdir($dir, 0777, true); } ?> |
The problem with the file_exists() function is that it returns true if there’s already a file with the specified filename. A better alternative to checking whether a filename is a directory is to use the is_dir() function. It returns true if the specified file is an existing directory and false otherwise.
|
1 2 3 4 5 6 7 |
<?php $dir = '/path/to/directory/'; if (!is_dir($dir)) { mkdir($dir, 0777, true); } ?> |
You may want to create a utility function to create a directory. For example, the following solution creates the makeDir() function, which returns true if and only if the directory already exists or is successfully created, and false otherwise.
|
1 2 3 4 5 6 7 8 |
<?php function makeDir($path) { return is_dir($path) || mkdir($path, 0777, true); } $dir = '/path/to/directory/'; makeDir($dir); ?> |
That’s all there is to creating a directory if it doesn’t already exist in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)