开发者

PHP delete all subdirectories in a directory having expired date?

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:

开发者_Python百科$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?
                     }
             }


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜