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

Date Posted: January 12, 2017, 3:57 pm


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 */ 
}

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me