How can I get files from a directory and show them by date / time using PHP?

I am looking for a way to show all my XML files in a directory. Glob doesn't sort by date, at least I don’t think, and it can only be used in the same directory ... How can I do this?

+3
source share
2 answers

You can use glob very well, but you need additional code to sort then:

$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);

This will give you an associative array of forms $filename => $timestamp.

+3
source

Not entirely beautiful, but may allow additional features:

<?php
    // directory to scan
    $dir = 'lib';

    // put list of files into $files
    $files = scandir($dir);

    // remove self ('.') and parent ('..') from list
    $files = array_diff($files, array('.', '..'));

    foreach ($files as $file) {
        // make a path
        $path = $dir . '/' . $file;

        // verify the file exists and we can read it
        if (is_file($path) && file_exists($path) && is_readable($path)) {
            $sorted[] = array(
                'ctime'=>filectime($path),
                'mtime'=>filemtime($path),
                'atime'=>fileatime($path),
                'filename'=>$path,
                'filesize'=>filesize($path)
            );
        }
    }

    // sort by index (ctime)
    asort($sorted);

    // reindex and show our sorted array
    print_r(array_values($sorted));
?>

Conclusion:

Array
(
    [0] => Array
        (
            [ctime] => 1289415301
            [mtime] => 1289415301
            [atime] => 1299182410
            [filename] => lib/example_lib3.php
            [filesize] => 36104
        )

    [1] => Array
        (
            [ctime] => 1297202755
            [mtime] => 1297202722
            [atime] => 1297202721
            [filename] => lib/example_lib1.php
            [filesize] => 16721
        )

    [2] => Array
        (
            [ctime] => 1297365112
            [mtime] => 1297365112
            [atime] => 1297365109
            [filename] => lib/example_lib2.php
            [filesize] => 57778
        )

)
+1
source

All Articles