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?
CodePudding user response:
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)";
}
}
CodePudding user response:
Your code has some typos like filetime
instead of filemtime
, etc. I corrected it:
$dirpath = "Dir/foo/bar/";
$files = [];
$files = glob($dirpath . "*");
rsort($files);
$today = date("Y-m-d");
$lastYear = date("Y-m-d", strtotime("-1 years"));
$todayTimeStamp = strtotime($today);
$beginningTimeStamp = strtotime($lastYear);
foreach ($files as $item) {
print "<br>" . filemtime($item) . '<hr>';
if (filemtime($item) > $beginningTimeStamp && filemtime($item) < $todayTimeStamp) {
echo "basename($item)";
}
}
I also corrected the if statement and also $beginningTimeTtamp
had a typo -> $beginningTimeStamp