PHP make directory or create year months folders

Every website contains directories to hold files or other folders in its structure. Also some websites need to allow users to dynamically create directories and upload files inside them. Like in a WordPress website, photos added in posts inside dashboard post editor are kept in dynamically generated year months directories inside wp-content/uploads directory by default. This blog will assist you to make directory in PHP and we will then create year months folders at our server.

PHP make directory with mkdir()

PHP’s mkdir() functions allows us to dynamically create directories. Its syntax is

mkdir(path, mode, recursive, context)

  • The first parameter is path including name of directory to create.
  • Second one is permission which, by default is 0777 (the widest possible access).
  • Third parameter ‘recursive‘ (default FALSE), allows the creation of nested directories specified in the ‘path‘.

This functions returns Boolean value depending upon success/failure of creation of directory.

To make directory ‘uploads‘ same at the level where script resides, we just need to write the following code below:

<?php mkdir('uploads'); ?>

Create year months folders

Now as we wish to create year months folders in a directory called uploads, we just need to run a loop 12 times for 12 months in a year and have to set recursive parameter to TRUE as specified in the code below:

Now browse the location where the script situated and you will find directories 01, 02,…..12 inside uploads/2015/ as the year is 2015 at the time of writing this post.

You Might Interested In