Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete files from directory based on creation date in php?

Tags:

php

I think you could go about this by looping through the directory with readdir and delete based on the timestamp:

<?php
$path = '/path/to/files/';
if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) { 
        $filelastmodified = filemtime($path . $file);
        //24 hours in a day * 3600 seconds per hour
        if((time() - $filelastmodified) > 24*3600)
        {
           unlink($path . $file);
        }

    }

    closedir($handle); 
}
?>

The if((time() - $filelastmodified) > 24*3600) will select files older than 24 hours (24 hours times 3600 seconds per hour). If you wanted days, it should read for example 7*24*3600 for files older than a week.

Also, note that filemtime returns the time of last modification of the file, instead of creation date.


It should be

if((time()-$filelastmodified) > 24*3600 && is_file($file))

to avoid errors for the . and .. directories.


The below function lists the file based on their creation date:

private function listdir_by_date( $dir ){
  $h = opendir( $dir );
  $_list = array();
  while( $file = readdir( $h ) ){
    if( $file != '.' and $file != '..' ){
      $ctime = filectime( $dir . $file );
      $_list[ $file ] = $ctime;
    }
  }
  closedir( $h );
  krsort( $_list );
  return $_list;
}

Example:

$_list = listdir_by_date($dir);

Now you can loop through the list to see their dates and delete accordingly:

$now = time();
$days = 1;
foreach( $_list as $file => $exp ){
  if( $exp < $now-60*60*24*$days ){
    unlink( $dir . $file );
  }
}

Try SplIterators

// setup timezone and get timestamp for yesterday
date_default_timezone_set('Europe/Berlin'); // change to yours
$yesterday = strtotime('-1 day', time());

// setup path to cache dir and initialize iterator
$path      = realpath('/path/to/files'); // change to yours
$objects   = new RecursiveIteratorIterator(
                 new RecursiveDirectoryIterator($path));

// iterate over files in directory and delete them
foreach($objects as $name => $object){
    if ($object->isFile() && ($object->getCTime() < $yesterday)) {
        // unlink($object);
        echo PHP_EOL, 'deleted ' . $object;
    }
}

Creation Time is only available on Windows.