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:
$parent = 'uploads/';
for($i = 1; $i <= 12; $i++)
$i = str_pad($i, 2, '0', STR_PAD_LEFT);
$the_dir = $parent.$dir.'/'.$i;
mkdir($the_dir, 0777, TRUE);
$year = date('Y');
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.