Yogesh Chauhan's Blog

WordPress: How to create a folder if it doesn’t already exist?

in WordPress on December 21, 2021

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

How can one check to see if a remote file exists using PHP?

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

Most Read

#1 How to add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Learn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHPSolution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software”MiscellaneousHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to display modal from bottom to top using CSS and JavaScript?CSSHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPAccessing and Setting features of JavaScript ObjectsJavaScript