user8406207
user8406207

Reputation:

Delete files older than specific month

I create that script:

$zips = glob("*.zip");

usort($zips, function($a, $b) { return filemtime($a) - filemtime($b); });

$dateFile = date("F d Y H:i:s", filectime($zips[0]));
$dateNow = date("F d Y H:i:s");

echo "dateFile = " . $dateFile;
echo "<br />";
echo "dateNow = " . $dateNow

Output is:

dateFile = August 03 2017 10:23:47
dateNow = August 03 2017 10:43:27

I want to check if file is older that month a.k.a dateNow - dateFile ? in months?

Upvotes: 1

Views: 1557

Answers (3)

yfain
yfain

Reputation: 496

You do it like the following

if(strtotime(dateFile) < strtotime('first day of last month', time())) {
   //file is older than 1 month
}

You can also use the function for 30 days from now. This will check if the file is older than 30 days backwards from the time you will do this condition.

if(strtotime(dateFile) < (time()-2592000)) {
   //file is older than 1 month
}

2592000 are 30 days in seconds.

Upvotes: 0

Caesar2011
Caesar2011

Reputation: 110

If you want to delete all files older than a month and you are on a linux machine, you can use a bash command to fulfil your request. On windows you need another command, but it works too.

this command finds all files older than 30 days in /path/to/files this folder and deletes them. Make sure that your path is correct or wrong files get deleted!

find /path/to/files* -mtime +30 -exec rm {} \;

I forgot to post the correct PHP code!

exec("find /path/to/files* -mtime +30 -exec rm {} \;");

Upvotes: -1

aidinMC
aidinMC

Reputation: 1436

get diff from current date and file date ; and check if older than 30 days delete it:

$date1 = date_create(date("Y-m-d")); // current date
$date2 = date_create($file_date); // change file date to Y-m-d format
$diff  = date_diff($date1,$date2);
if($diff->format("%R") == '+' && $diff->format("%a") != 0){
    if($diff->format("%a") > 30)
        //delete file
}else
    //delete file

Upvotes: 0

Related Questions