Php - Get Last Modified Directory

A bit stuck in this and hopes for some help. I am trying to get the last modified directory from a path in a string. I know that there is a function called " is_dir ", and I have done some research, but it seems it cannot make anything work.

I do not have a code, sorry.

<?php
 $path = '../../images/'; 
 // echo out the last modified dir from inside the "images" folder
?>

For example: In the above path variable there are 5 subfolders inside the "images" directory. I want to output "sub5" - this is the last modified folder.

+4
source share
3 answers

You can use scandir()a function instead is_dir().

Here is an example.

function GetFilesAndFolder($Directory) {
    /*Which file want to be escaped, Just add to this array*/
    $EscapedFiles = [
        '.',
        '..'
    ];

    $FilesAndFolders = [];
    /*Scan Files and Directory*/
    $FilesAndDirectoryList = scandir($Directory);
    foreach ($FilesAndDirectoryList as $SingleFile) {
        if (in_array($SingleFile, $EscapedFiles)){
            continue;
        }
        /*Store the Files with Modification Time to an Array*/
        $FilesAndFolders[$SingleFile] = filemtime($Directory . '/' . $SingleFile);
    }
    /*Sort the result as your needs*/
    arsort($FilesAndFolders);
    $FilesAndFolders = array_keys($FilesAndFolders);

    return ($FilesAndFolders) ? $FilesAndFolders : false;
}

$data = GetFilesAndFolder('../../images/');
var_dump($data);

Files Folders .

, is_dir() 2 , $FilesArray=[] $FolderArray=[].

filemtime() scandir() arsort()

+2

:

<?php

// Get an array of all files in the current directory.
// Edit to use whatever location you need
$dir = scandir(__DIR__);

$newest_file = null;
$mdate = null;

// Loop over files in directory and if it is a subdirectory and
// its modified time is greater than $mdate, set that as the current
// file.
foreach ($dir as $file) {
    // Skip current directory and parent directory
    if ($file == '.' || $file == '..') {
        continue;
    }
    if (is_dir(__DIR__.'/'.$file)) {
        if (filemtime(__DIR__.'/'.$file) > $mdate) {
            $newest_file = __DIR__.'/'.$file;
            $mdate = filemtime(__DIR__.'/'.$file);
        }
    }
}
echo $newest_file;
+2

This will work just like the other answers. Thank you all for your help!

<?php

    // get the last created/modified directory

    $path = "images/";

    $latest_ctime = 0;
    $latest_dir = '';    
    $d = dir($path);

    while (false !== ($entry = $d->read())) {
    $filepath = "{$path}/{$entry}";

    if(is_dir($filepath) && filectime($filepath) > $latest_ctime) {
      $latest_ctime = filectime($filepath);
      $latest_dir = $entry;
    }

    } //end loop

    echo $latest_dir;

    ?>
+1
source

Source: https://habr.com/ru/post/1688045/


All Articles