简体   繁体   中英

Simple PHP Delete All Files Except the 3 last days -

There is a FTP user and a DIR : /home/user/public_html/ backups /

Everyday on 03:00 a folder with date and in that folder a file of 3,5GB will be added automatically there trough FTP. Now if there will be added 3,5GB everyday in the map backups that will be 49GB in 14 days.

And about 14 days i will be have this Folder structure:

2015-12-18
2015-12-17
2015-12-16
2015-12-15
2015-12-14
2015-12-13
2015-12-13
2015-12-12
2015-12-11
2015-12-10
2015-12-09
2015-12-08

So i was thinking to make a cronjob script for this, that every sunday night on 00:00u a .php will be excuted automatically with a cronjob.

Example on: 2015-12-18 a .php script will be executed, and that all folders will deleted except the last 3 added folders: 2015-12-18 - 2015-12-17 - 2015-12-16

The .php script will delete all files EXPECT the last 3 added folders/files in the map Backups

Is this posibble with .PHP? So yes, does someone have a sample script for me? Or can it be done with a better solution?

Here is it. You populate an array of all directories using glob, you slice the array to remove the last 3 items, and you delete the others.

$files = glob('/tmp/*', GLOB_ONLYDIR);

$deletions = array_slice($files, 0, count($files) - 3);

foreach($deletions as $to_delete) {
    array_map('unlink', glob("$to_delete/*.*"));
    $deleted = rmdir($to_delete);
}

nix *,不需要php,你可以将其作为cronjob运行

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

I am not very familiar with a time on PHP haven't play for too much but I will do something like this :

if today is sunday will set todays date to a database as a date that was last time deleted , then make some simple code witch checks how many days passed or seconds or what ever and if passed like a 7 days will delete everything from a database except last try days added items that's kind a simple I think `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM