PHP: Create directory based on current date.

This is a PHP tutorial on how to create directories and sub-directories that are based on the current date. These kind of “YYYY/MM/DD” folder structures are pretty common, especially in web apps that allow users to upload files.

Here is a simple example:

<?php

//Year in YYYY format.
$year = date("Y");

//Month in mm format, with leading zeros.
$month = date("m");

//Day in dd format, with leading zeros.
$day = date("d");

//The folder path for our file should be YYYY/MM/DD
$directory = "$year/$month/$day/";

//If the directory doesn't already exists.
if(!is_dir($directory)){
    //Create our directory.
    mkdir($directory, 755, true);
}

An explanation of the PHP code above:

  1. We get the current year using PHP’s date function.
  2. We get the current month.
  3. We get the current day.
  4. We combine our date variables into a directory structure.
  5. We create the directory if it doesn’t already exist.

Today’s date is the 26th of November, 2015. When I run the code above, it creates the directory structure “2015/11/26”.

If you’re dealing with a large number of incoming files, you may want to add the current hour as a sub-directory as well:

<?php

$directory = date("Y").'/'.date("m").'/'.date("d").'/'.date('H').'/';

//If the directory doesn't already exists.
if(!is_dir($directory)){
    //Create our directory.
    mkdir($directory, 755, true);
}

I ran the above code and the following directory structure was created:

2015/11/26/16/

Note that 16 is 4PM in 24-hour format. If a user uploads a file at 10.25AM on Christmas Day, then the structure will look like so:

2015/12/25/10/

Why place files into different sub-directories?

When a folder contains too many files, it can cause performance issues. For instance, on Windows, the Explorer program can freeze up as it attempts to display meta data for each file. Web-based file browsers can also run into issues when there are too many files in the same folder. It is also handy in the sense that if you need to manually search for a specific file, knowing the date that it was uploaded on will narrow down your search.