Backing up a File Before Overwriting It (in Drupal 7)

I’m communicating with a 3rd party SOAP API to pull some data into a CSV file. The CSV file will be used by Feeds and/or Migrate so it’s important to have the file named exactly the same for each run. I want the generated CSV to always be named “mdb_interests.csv” but I want to “backup” the existing “mdb_interests.csv” to “mdb_interests_N.csv” if one already exists. This will ensure that we always have the latest data in “mdb_interests.csv” but will have backups from all previous API pulls. Using some built-in Drupal functions it’s pretty simple:

NOTE: If the first file_unmanaged_move() does move an existing file for you, the date of the new “incremented” file will change to the current date. There are ways to fix this but I don’t need to for this project, so…

You can also make a function that is a bit more “reusable”:

 

Tagged with:
Posted in Tech Tips

Leave a Reply

Your email address will not be published. Required fields are marked *

*