This is a quick PHP tutorial on how to create a folder or directory if it doesn’t already exist. In certain use cases, you may have to use PHP to dynamically create folders on the fly (this is often the case when dealing with user uploads).
The first example is pretty easy. In this scenario, we want to create a folder called “images”:
<?php //The name of the directory that we need to create. $directoryName = 'images'; //Check if the directory already exists. if(!is_dir($directoryName)){ //Directory does not exist, so lets create it. mkdir($directoryName, 0755); }
An explanation of the PHP code snippet above:
- We set the name of the directory that we want to create. In this case, it is “images”.
- We used PHP’s is_dir function to check if the folder already exists. If the is_dir function returns a boolean FALSE value, then we know that the directory in question doesn’t already exist.
- If the directory doesn’t already exist, we can create it using the mkdir function.
Note that if you fail to check for the directory’s existence, you run the risk of getting a nasty PHP warning:
Warning: mkdir(): File exists in path/to/file.php on line 9
You can also create multiple sub-folders at the same time:
//The name of the directory that we need to create. $directoryName = './images/users/uploads/'; //Check if the directory already exists. if(!is_dir($directoryName)){ //Directory does not exist, so lets create it. mkdir($directoryName, 0755, true); }
In this example:
- We set the directory name to “./images/users/uploads/”.
- We set the third parameter on mkdir to TRUE. The third parameter for mkdir is “Recursive: Allows the creation of nested directories specified in the pathname.”
If the “users” and “uploads” sub-directories do not exist, then mkdir will automatically create them.