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.


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.



file_exists checks whether a file or directory exists.

Similar Post

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



$filepath is string. It returns true if the filename exists otherwise it returns false.


mkdir attempts to create a directory/folder.


    string $directory,
    int $permissions = 0777,
    bool $recursive = false,
    resource $context = ?


  • $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 check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
How to create a CSS full page background image?CSSHow to vertically align a html radio button to it’s label?CSSHow does while loop work in SCSS?SCSSLearn how to use Self JOIN in SQL and MySQLSQL/MySQLHow to enable GD library support for PHP on windows server?PHPclip and clip-path properties in CSSCSS