Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Show files from within a folder via PHP.

0
by qroft, last modified on May 27th, 2024

On my page i wanted to show a collection of Wallpapers per year, that i collect and constantly update. Until now i did it through the Winter.Blog plugin but found that a bit too heavy for such a small feature. Apart of that i wanted to automate it more, and this is what i came up with. Please be informed that i am a scriptkid and not a 100% good developer, so the code below certainly can be optimized, but it might lead you into the right direction.

IDEA Upload an image to a folder and a WinterCMS page or partial checks said folder and shows the files automatically. Use anyone of the codes within the PHP Code section of a page.

SOLUTION 1 (OLDSCHOOL VANILLA)

function onStart()
{
    /*
    $directory = "./".media_path()."/wallpaper/".date("Y");
    $files2 = scandir( $directory, SCANDIR_SORT_DESCENDING);
    $this['newest_file'] = "/wallpaper/".date("Y")."/".$files2[0];

    $files = scandir($directory);
    $lastModifiedTime = array();
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $filepath = $directory . DIRECTORY_SEPARATOR . $file;
            $lastModifiedTime[$file] = filemtime($filepath);
        }
    }
    arsort($lastModifiedTime);
    $wallies = [];
    foreach ($lastModifiedTime as $file => $mtime) {
        //echo "File: $file - Date Modified: " . date('Y-m-d H:i:s', $mtime);
        array_push($wallies, $file);
    }

    $this['wallies'] = "/wallpaper/".date("Y")."/".$wallies[0];

SOLUTION 2: Via ListFolderContents

    $currYear = date("Y");

    $folder = '/wallpaper/'.$currYear;
    $mediaLib = \System\Classes\MediaLibrary::instance();
    //$files = $mediaLib->listFolderContents($folder, 'size'); //lastModified

    $files = $mediaLib->listFolderContents($folder, ['by' => "modified", 'direction' => "desc"] ); //lastModified
    $this['mediaFiles'] = $files

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?