【发布时间】:2022-01-18 02:29:43
【问题描述】:
我希望能够仅使用 PHP 删除目录中超过 7 天的所有文件。我怎样才能做到这一点?服务器正在使用 Debian Linux。
【问题讨论】:
我希望能够仅使用 PHP 删除目录中超过 7 天的所有文件。我怎样才能做到这一点?服务器正在使用 Debian Linux。
【问题讨论】:
<?php
// (A) DELETE ONLY IF OLDER THAN SET DATE
function delold ($keepDate, $folder) {
// (A1) GET ALL FILES INSIDE FOLDER
$files = glob("$folder*", GLOB_BRACE);
// (A2) LOOP, CHECK LAST MODIFIED, DELETE
if (count($files)>0) {
$keepDate = strtotime($keepDate);
foreach ($files as $f) { if (filemtime($f) < $keepDate) {
echo unlink($f)
? "$f deleted\r\n"
: "Error deleting $f\r\n" ;
}}
}
}
// (B) GO!
// DATE FORMAT YYYY-MM-DD... OR ANYTHING THAT STRTOTIME CAN UNDERSTAND
delold("2020-11-10", "d:/test/");
【讨论】:
604800 是一周中的秒数。
$path="whateverdir/";
(time()-filectime($path.$file)) > 604800;
unlink($path.$file);
如果您有多个目录,则必须为每个目录执行此操作。
【讨论】:
一个简单的 PHP 函数,用于删除超过给定年龄的文件。轮换备份或日志文件非常方便,例如...
<?php
/**
* A simple function that uses mtime to delete files older than a given age (in seconds)
* Very handy to rotate backup or log files, for example...
*
* $dir String whhere the files are
* $max_age Int in seconds
* return String[] the list of deleted files
*/
function delete_older_than($dir, $max_age) {
$list = array();
$limit = time() - $max_age;
$dir = realpath($dir);
if (!is_dir($dir)) {
return;
}
$dh = opendir($dir);
if ($dh === false) {
return;
}
while (($file = readdir($dh)) !== false) {
$file = $dir . '/' . $file;
if (!is_file($file)) {
continue;
}
if (filemtime($file) < $limit) {
$list[] = $file;
unlink($file);
}
}
closedir($dh);
return $list;
}
// An example of how to use:
$dir = "/my/backups";
$to = "my@email.com";
// Delete backups older than 7 days
$deleted = delete_older_than($dir, 3600*24*7);
$txt = "Deleted " . count($deleted) . " old backup(s):\n" .
implode("\n", $deleted);
mail($to, "Backups cleanup", $txt);
【讨论】: