, , ,

I have written a small piece of code for deleting the old files from a directory with the help of filemtime() function. Following piece of code delete the 10 days old files from a root directory. This scripts only delete old files at the root folder not delete files from sub folders. For deleting the sub folders files also we need to modified this script by using recursive function.

Example :

$dir = '/var/www/html/AP/test/';

echo "STARTING<br/>";
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
      while ($file = readdir($dh)) {
         if(!is_dir($dir.$file)) {
            //if 10 days old, delete
            if (filemtime($dir.$file) < strtotime('-10 days')) { 
               echo "Deleting ".$dir.$file." (old) :";
               echo "(date->".date('Y-m-d',filemtime($dir.$file)).")<br/>";
   } else {
      echo "ERROR. Could not open directory: $dir<br/>";
} else {
   echo "ERROR. Specified path is not a directory: $dir<br/>";
echo "DONE<br/>";