Link to home
Start Free TrialLog in
Avatar of john-formby
john-formbyFlag for Ghana

asked on

PHP delete files older than 5 days from directory and all sub-directories

Hi,

I need a little bit of help.  I need to write a script that will look through all directories and sub-directories and delete any files that are more than 5 days old.  I can get it to delete files from the top level images directory (root/images/), but I don't know how to get it to check in the sub-diretories.

My structure is as follows:

root > index.php
root/images > some files
root/images/sub1 > some files
root/images/sub1/subsub1 > some files
root/images/sub2 > some files

The code so far is:

<?php
$files = array();
$index = array();
$timeago = strtotime('-5 days');

if ($handle = opendir('images')) {
	clearstatcache();
	while (false !== ($file = readdir($handle))) {
   		if ($file != "." && $file != "..") {
   			$files[] = $file;
			$index[] = filemtime( 'images/'.$file );
   		}
	}
  	closedir($handle);
}
	
asort( $index );
	
foreach($index as $i => $t) {	
	if($t < $timeago) {
		@unlink('images/'.$files[$i]);
	}
}
?>

Open in new window


Please can someone point me in the right direction?

Thank you for your time,

John
Avatar of Ahmed Merghani
Ahmed Merghani
Flag of Sudan image

Try this:

<?php
function delete_all($directory){
$files = array();
$index = array();
$timeago = strtotime('-5 days');

if ($handle = opendir($directory)) {
	clearstatcache();
	while (false !== ($file = readdir($handle))) {
   		if ($file != "." && $file != "..") {
   			$files[] = $file;
			$index[] = filemtime($directory.'/'.$file );
                        if(is_dir($file)) delete_all($directory.'/'.$file); 
   		}
	}
  	closedir($handle);
}
	
asort( $index );
	
foreach($index as $i => $t) {	
	if($t < $timeago) {
		@unlink('images/'.$files[$i]);
	}
}
}
delete_all('images');
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry some modifications:
<?php
function delete_all($directory){
$files = array();
$index = array();
$timeago = strtotime('-5 days');

if ($handle = opendir($directory)) {
	clearstatcache();
	while (false !== ($file = readdir($handle))) {
   		if ($file != "." && $file != "..") {
   			$files[] = $file;
			$index[] = filemtime($directory.'/'.$file );
                        if(is_dir($file)) delete_all($directory.'/'.$file); 
   		}
	}
  	closedir($handle);
}	
foreach($index as $i => $t) {	
	if($t < $timeago) {
		@unlink($directory.'/'.$files[$i]);
	}
}
}
delete_all('images');
?>

Open in new window

Avatar of john-formby

ASKER

I tried all three posts but this was the only one that removed the old files from all sub-directories.  Thanks so much for this solution, it has really helped me out :-)