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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #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
How to create a new HTML element programmatically using JavaScript?HTMLPHP arrays for US states’ full names and abbreviationsPHP5 Key Principles Of Good Website UsabilityUI/UX3 Common Usability Mistakes In Web DesignUI/UXCONCAT and CONCAT_WS Functions in PostgresPostgressubstring() Method in JavaScriptJavaScript