SOLVED (forgot it was an associative array):
foreach($list_s as $file => $timestamp) {
echo $file;
unlink($dir_files . $file);
unlink($dir_sql . $file);
}
I have a backup area and I want every time the user visits it for it to run a code that only keeps n
(user specified amount of backups to be kept) numbers of the newest backups.
I am pretty sure I have the underlying logic correct with array_slice
. But the code does not delete the files, and I cannot pin-point where the issue is.
function listdir_by_date($dir)
{
$h = opendir($dir);
$_list = array();
while ($file = readdir($h)) {
if ($file != '.' and $file != '..') {
$ctime = filectime($dir . $file);
$_list[$file] = $ctime;
}
}
closedir($h);
// reorder: associative array in asc order
ksort($_list);
return $_list;
}
$sql = Nemesis::select('backup_amt', 'config');
list($backup_amt) = $sql->fetch_row();
$list = listdir_by_date($dir_sql);
$file = readdir($dir_sql);
if (count($list) > $backup_amt && is_numeric($backup_amt)) {
/* we delete the user specified backup by the backup amt
say we have 5, user specified only 2 backups to be kept
we delete the last 3 backups */
$list_s = array_slice($list, 0, count($list) - $backup_amt);
foreach ($list_s as $file => $timestamp) {
@unlink($dir_files . $file);
@unlink($dir_sql . $file);
}
}