There are many situations that you might need to check if the folder exists and if not, you might want to create one.
For e.g. some servers don’t create basic WordPress folders and you might want to have some basic folders to do whatever you want to do! Sometimes, you want to create additional folders but want to make sure that it’s not already there or the errors will be displayed on the frontend or backend side.
Solution
We can make use of a PHP functions file_exists(to check if the folder exists) and mkdir(to create the folder).
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Let’s understand the solution one by one.
Explanation
file_exists
file_exists checks whether a file or directory exists.
Similar Post
Syntax
file_exists($filepath)
$filepath is string. It returns true if the filename exists otherwise it returns false.
mkdir
mkdir attempts to create a directory/folder.
Syntax
mkdir(
string $directory,
int $permissions = 0777,
bool $recursive = false,
resource $context = ?
)
where
- $directory is the directory path
- $permissions value is 0777 by default, which means the widest possible access
- $recursive allows the creation of nested directories
- $context is a context stream resource
directories file_exists folder functions php solution