PHP delete all subdirectories in a directory having expired date?

2.8k views Asked by At

There is a directory /home/example/public_html/users/files/. Within the directory there are subdirectories with random names like 2378232828923_1298295497.

How do I completely delete the subdirectories which have creation date > 1 month?

There is a good script that I use to delete files, but it don't work with dirs:

$seconds_old = 2629743; //1 month old
$directory = "/home/example/public_html/users/files/";

            if( !$dirhandle = @opendir($directory) )
                        return;

             while( false !== ($filename = readdir($dirhandle)) ) {
                     if( $filename != "." && $filename != ".." ) {
                                $filename = $directory. "/". $filename;

                             if( @filectime($filename) < (time()-$seconds_old) )
                                      @unlink($filename); //rmdir maybe?
                     }
             }
3

There are 3 answers

0
Carlos Campderrós On BEST ANSWER

you need a recursive function for this.

function remove_dir($dir)
{
    chdir($dir);
    if( !$dirhandle = @opendir('.') )
        return;

    while( false !== ($filename = readdir($dirhandle)) ) {
        if( $filename == "." || $filename = ".." )
            continue;

        if( @filectime($filename) < (time()-$seconds_old) ) {
            if (is_dir($filename)
                remove_dir($filename);
            else 
                @unlink($filename);
        }
    }
    chdir("..");
    rmdir($dir);
}
0
ayush On
 <?php
    $dirs = array();
    $index = array();
    $onemonthback = strtotime('-1 month');
    $handle = opendir('relative/path/to/dir');
    while($file = readdir($handle){
        if(is_dir($file) && $file != '.' && $file != '..'){
            $dirs[] = $file;
                $index[] = filemtime( 'relative/path/to/dir/'.$file );
        }
}    
closedir($handle);


    asort( $index );

    foreach($index as $i => $t) {

        if($t < $onemonthback) {
            @unlink('relative/path/to/dir/'.$dirs[$i]);
        }


}
?>
2
lucaferrario On

If PHP runs on a Linux server, you could use a shell command, to improve performance (a recursive PHP function can be inefficient in very large directories):

shell_exec('rm -rf '.$directory);