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?
2
Answers
Your code has some typos like
filetime
instead offilemtime
, etc. I corrected it:I also corrected the if statement and also
$beginningTimeTtamp
had a typo ->$beginningTimeStamp
Several issues. You want to use timestamps. There’s no reason to create timestamps, format them and then convert them back to timestamps. Also, there’s an error in the
if
. This will work:However, unless something might have a weird time in the future, you just need: