Organize Diretory Files into Year-Month-Day Heirarchy using PHP

Do you have large amount of files sitting in just one directory? Have you ever thought about organizing them in Year-Month-Day path programatically?

What the code bellow does is it loops through each file on the specified directory then takes the date the file was created and formats it into a path, ex. 2017/January/12, now that we know the path – we can use it for creating the directory heirarchy tree. If the path does not exist yet – we create it. After the path is created, we then move the file inside it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$image_folder = 'images/';
$files = glob( $image_folder . '*.{jpg,png,gif}', GLOB_BRACE) ;

foreach( $files as $file ) {
    $time_stamp = filemtime( $file ); /* Get date create of the file */
    $path_date = date( 'Y/F/d', $time_stamp ); /* Returns the format: [Year]/[Month]/[Day] */
   
    /* Create path if not yet existing */
    if ( ! file_exists( $image_folder . $path_date ) ) {
        mkdir( $image_folder . $path_date, 0777, true );
    }
   
    /* Use "rename" instead of "copy" if you want to MOVE the file */
    copy( $file, $image_folder . $path_date . '/' . explode( 'images/', $file )[1] );
   
    /* Do database update here if necessary */ 
}


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me