如果PHP中的条件为真,如何从目录中删除旧文件?
我只想在一个文件夹中保留10个最新文件,并删除其他文件。 我创建了一个脚本,如果文件号大于10,则只删除最旧的文件。 如何使此脚本适应我的需要如果PHP中的条件为真,如何从目录中删除旧文件?,php,delete-file,Php,Delete File,我只想在一个文件夹中保留10个最新文件,并删除其他文件。 我创建了一个脚本,如果文件号大于10,则只删除最旧的文件。 如何使此脚本适应我的需要 $directory = "/home/dir"; // Returns array of files $files = scandir($directory); // Count number of files and store them to variable.. $num_files = count($files)-2; if($num_fi
$directory = "/home/dir";
// Returns array of files
$files = scandir($directory);
// Count number of files and store them to variable..
$num_files = count($files)-2;
if($num_files>10){
$smallest_time=INF;
$oldest_file='';
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
$time=filemtime($directory.'/'.$file);
if (is_file($directory.'/'.$file)) {
if ($time < $smallest_time) {
$oldest_file = $file;
$smallest_time = $time;
}
}
}
closedir($handle);
}
echo $oldest_file;
unlink($oldest_file);
}
$directory=“/home/dir”;
//返回文件数组
$files=scandir($directory);
//计算文件数并将其存储到变量。。
$num_files=计数($files)-2;
如果($num_files>10){
$INTIME=INF;
$oldest_文件=“”;
如果($handle=opendir($directory)){
while(false!=($file=readdir($handle))){
$time=filemtime($directory.'/'.$file);
如果(是_文件($directory.'/'.$file)){
如果($时间<$最小时间){
$oldest_file=$file;
$time=$time;
}
}
}
closedir($handle);
}
echo$u文件;
取消链接($u文件);
}
基本脚本,为您提供想法。将所有文件及其时间推送到一个数组中,按时间降序排序并遍历if($count>10)
表示何时开始删除,即当前保留最新的10
<?php
$directory = ".";
$files = array();
foreach(scandir($directory) as $file){
if(is_file($file)) {
//get all the files
$files[$file] = filemtime($file);
}
}
//sort descending by filemtime;
arsort($files);
$count = 1;
foreach ($files as $file => $time){
if($count > 10){
unlink($file);
}
$count++;
}
您只需按返回文件的修改日期对scandir
的结果进行排序:
/**
* @return string[]
*/
function getOldestFiles(string $folderPath, int $count): array
{
// Grab all the filenames
$filenames = @scandir($folderPath);
if ($filenames === false) {
throw new InvalidArgumentException("{$folderPath} is not a valid folder.");
}
// Ignore folders (remove from array)
$filenames = array_filter($filenames, static function (string $filename) use ($folderPath) {
return is_file($folderPath . DIRECTORY_SEPARATOR . $filename);
});
// Sort by ascending last modification date (older first)
usort($filenames, static function (string $file1Name, string $file2Name) use ($folderPath) {
return filemtime($folderPath . DIRECTORY_SEPARATOR . $file1Name) <=> filemtime($folderPath . DIRECTORY_SEPARATOR . $file2Name);
});
// Return the first $count
return array_slice($filenames, 0, $count);
}
注意:就本回答而言,这显然是过度评论。将所有文件放入一个数组(名称和时间),排序并删除您需要的内容。$files
已经是一个数组了。为什么不使用它而不是使用opendir
?
$folder = '/some/folder';
$oldestFiles = getOldestFiles($folder, 10);
foreach ($oldestFiles as $file) {
unlink($folder . '/' . $file);
}