Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP get files in directory and list if they are within the last year (filetime)

I need to output the contents of a directory only if the file has been created within the last year.

<?php
    $dirpath = "Dir/foo/bar/";
    $files = array();
    $files = glob($dirpath . "*");
    rsort($files);
    $today = date("Y-m-d");
    $lastYear = date("Y-m-d", strtotime("-1 years"));
    $todayTimeStamp = strtotime($today);
    $beginningTimeTtamp = strtotime($lastYear);
    foreach($files as $item) {
        if(filetime($item)  > $beginningTimeStamp && < $todayTimeStamp) {
            echo "basename($item)";
         }
     }

This doesn’t return anything – I just want to return $item that is greater than the date a year from today and less than today (not necessary?).

Am I wrong converting the $beginningTimeStamp and $todayTimeStamp to a timestamp to compare filetime? Im not able to convert each $item to its filetime… Is there a better way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Several issues. You want to use timestamps and there is an error in the if. This will work:

foreach($files as $item) {
    $mt = filemtime($item)
    if($mt > strtotime('-1 year') && $mt < time()) {
        echo "basename($item)";
     }
 }

However, unless something might have a weird time in the future, you just need:

foreach($files as $item) {
    if(filemtime($item) > strtotime('-1 year') {
        echo "basename($item)";
     }
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading