Question

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?
                     }
             }
Was it helpful?

Solution

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);
}

OTHER TIPS

 <?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]);
        }


}
?>

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top