我在xampp中有一个文件夹结构
Deletefiles
--Uploads
--Test1
--Test2
--index.php
index.php我编写脚本来删除上传中的所有文件夹及其内容,例如test1和test2
$foldername = array('test1','test2');
function recursiveRemove($dir) {
$structure = glob(rtrim($dir, "/").'/*');
if (is_array($structure)) {
foreach($structure as $file) {
if (is_dir($file)) recursiveRemove($file);
elseif (is_file($file)) unlink($file);
}
}
rmdir($dir);
}
foreach($foldername as $fname){
recursiveRemove("uploads/".$fname."/");
}
它的工作正常。但我只想删除超过2天的文件夹。如何更改我的脚本。
答案 0 :(得分:1)
正如@Dagon指出你需要在删除之前验证文件对象的日期。
将此添加到您的foreach
。条件将询问文件对象的日期是否小于当前时间减去60秒* 60(分钟)* 24(小时)* 2(天)。
foreach($structure as $file) {
if (filemtime($file) < time() - (60 * 60 * 24 * 2) ) {
if (is_dir($file)) recursiveRemove($file);
elseif (is_file($file)) unlink($file);
}
}
请注意,您的递归函数不会删除与条件匹配的条件(超过2天)不匹配条件(超过2天)。(2天以内)。
如果rmdir
不为空,则发出警告。
答案 1 :(得分:0)
您可以尝试这样
function recursiveRemove($dir) {
$structure = glob(rtrim($dir, "/").'/*');
if (is_array($structure)) {
foreach($structure as $file) {
if (is_dir($file)) {
recursiveRemove($file);
} elseif (is_file($file)) {
$lastmod = filemtime($file);
//48 hours in a day * 3600 seconds per hour
if((time() - $lastmod) > 48*3600) {
unlink($file);
}
}
}
}
$dirlastmod = filemtime($dir);
if((time() - $dirlastmod) > 48*3600) {
rmdir($dir);
}
}
foreach($foldername as $fname){
recursiveRemove("uploads/".$fname."/");
}