[英]PHP delete all subdirectories in a directory having expired date?
There is a directory /home/example/public_html/users/files/
. 有一个目录/home/example/public_html/users/files/
。 Within the directory there are subdirectories with random names like 2378232828923_1298295497
. 在目录中,有子目录具有随机名称,如2378232828923_1298295497
。
How do I completely delete the subdirectories which have creation date > 1 month? 如何完全删除创建日期大于1个月的子目录?
There is a good script that I use to delete files, but it don't work with dirs: 我使用了一个不错的脚本来删除文件,但不适用于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?
}
}
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]);
}
}
?>
如果PHP在Linux服务器上运行,则可以使用shell命令来提高性能(递归PHP函数在非常大的目录中可能效率不高):
shell_exec('rm -rf '.$directory);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.