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.

Download Code

 
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.

Download Code

 
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.

Download Code

 
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.

Download Code

That’s all there is to creating a directory if it doesn’t already exist in PHP.