如何限制文件夹的最大文件数


how to restrict maximum number of files for a folder

实际上,我通过php将数据库文件转储到我创建的导出文件夹中。在这里,我只想以FIFO的方式将最新的十个sql文件保存在导出文件夹中。我不想过多地填充文件夹,也不想把它限制在十个最新的文件中。怎么做?

例如,首先使用glob获取所有文件,然后确定目录中是否有十个或更多文件。之后,检查每个的mtime(修改时间),并删除最旧的一个。

$file_pattern = '/path/to/directory/and/files/*';
$filenames = glob( $file_pattern );
if ( count( $filenames ) > 9 ) {
    // While there are ten or more files.
    while ( count( glob( $file_pattern ) ) > 9 ) {
        $oldest_file = null;
        // Grab the unix timestamp of *now*, as filemtime returns a unix timestamp too.
        $current_oldest_time = time();
        foreach ( $filenames as $filename ) {
            $filetime = filemtime( $filename );
            if ( $filetime < $current_oldest_time ) {
                $current_oldest = $filetime;
                $oldest_file = $filename;
            }
        }
        // After the foreach you'll have the filename of the oldest file (remove it),:
        unlink( $oldest_file );
        // Or null if something went wrong (break out of the loop):
        break;
    }
}

您可以使用取消链接功能删除文件:http://php.net/manual/de/function.unlink.php

您只需要在目录

中找到最旧的文件