[英]PHP delete all subdirectories in a directory having expired date?
有一個目錄/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?
}
}
你需要為這個遞歸函數。
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.