john-formby
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:
Please can someone point me in the right direction?
Thank you for your time,
John
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]);
}
}
?>
Please can someone point me in the right direction?
Thank you for your time,
John
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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');
?>
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 :-)
Open in new window