简体   繁体   中英

how to delete old files in a directory using php

I have a directory for database backups, and a PHP script that makes a backup of the database every day. But after a month or so i will have 30 files in the backup directory. How can i write a PHP script that deletes old backup files every day so that there are always 10 backup files in my directory? when a new backup is stored, the oldest backup file will be deleted and so on ...

You can read the backups directory and delete every file that is older than 30 days. However, I personally create files dynamically, and every file has this format:

database_dump_DD-MM-YYYY_HH:MM:SS.sql

So I can delete the files considering the filename. Since I don't know what's the format of your files, you can delete them like this:

$files = readdir(opendir('backups')); //read directory for files

foreach($files as $file){
    if(filemtime($file) > (time() + 2592000)){ //check if the file is older than 30 days
        unlink($file); //delete
    }
}

After making the backup with the PHP backup you loop through the directory and then remove the oldest backup files:

$files = glob('backupfolder/*.bak');
if(count($files) > 10)
  foreach($files as $file)
    if(time() - filectime($file) > 10 * 24 * 60 * 60)
      unlink($file);

Why go to the effort of using PHP? find command and cron would do the trick

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