0

有一个目录/home/example/public_html/users/files/。在目录中,有随机名称的子目录,例如2378232828923_1298295497.

如何完全删除创建日期> 1个月的子目录?

有一个很好的脚本可以用来删除文件,但它不适用于 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?
                     }
             }
4

3 回答 3

0

为此,您需要一个递归函数。

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);
}
于 2011-02-21T14:26:46.633 回答
0
 <?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]);
        }


}
?>
于 2011-02-21T14:35:13.997 回答
0

如果 PHP 在 Linux 服务器上运行,您可以使用 shell 命令来提高性能(递归 PHP 函数在非常大的目录中可能效率低下):

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

于 2012-02-11T17:03:02.097 回答