如果条件在PHP中成立,如何从目录中删除旧文件? [英] How to delete the old files from a directory if a condition is true in PHP?

查看:93
本文介绍了如果条件在PHP中成立,如何从目录中删除旧文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在一个文件夹中保留10个最新文件,然后删除其他文件.我创建了一个脚本,如果文件号大于10,该脚本仅删除最旧的脚本.如何使该脚本适应我的需求?

I want to keep only 10 newest files in a folder and delete others. I created a script that deletes only the oldest ones if a file number is larger than 10. How can I adapt this script to my needs?

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

推荐答案

基本脚本可为您提供想法.将所有文件及其时间推入数组,按时间顺序降序排列并走入低谷. if($ count> 10)表示何时应开始删除操作,即当前它会保留最新的10.

Basic script to give you the idea. Push all the files with their times into an array, sort it by descending time order and walk trough. if($count > 10) says when the deletion should start, i.e. currently it keeps the newest 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++;
    }

这篇关于如果条件在PHP中成立,如何从目录中删除旧文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆