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?
>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)";
}
}