Php 删除“;旧的;根据文件时间戳在目录中备份

Php 删除“;旧的;根据文件时间戳在目录中备份,php,file,dir,delete-file,Php,File,Dir,Delete File,已解决(忘记它是关联数组): 我有一个备份区域,我希望每次用户访问该区域时,它都运行一个代码,该代码只保留最新备份的编号 我非常确定我的数组\u切片的底层逻辑是正确的。但代码并没有删除文件,我无法确定问题所在 function listdir_by_date($dir) { $h = opendir($dir); $_list = array(); while ($file = readdir($h)) { if ($file != '.' and $fi

已解决(忘记它是关联数组):

我有一个备份区域,我希望每次用户访问该区域时,它都运行一个代码,该代码只保留最新备份的编号

我非常确定我的
数组\u切片
的底层逻辑是正确的。但代码并没有删除文件,我无法确定问题所在

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);
    }
}

只是为了调试,您可以
打印($list)
foreach之前和
echo$file
内部foreach循环
数组([dbbackup_14.07.2013_00_50_23.sql]=>1373763023[dbbackup_14.07.2013_00_49_40.sql]=>137376762980)137376302313762980
该文件似乎是unix时间戳,但我不确定原因!好的,你现在可以处理它并找到问题所在
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);
    }
}