Monday 16 July 2018

PHP Snippet – Deleting Files Older Than X Days

PHP Snippet – Deleting Files Older Than X Days

Sometimes it is necessary to perform clean-up operations and only keep the latest files within a directory. If we take application logs for example, we might only want to keep the last 7 days worth of files. This keeps our system cleaner and prevents unnecessary disk space being taken up.
To keep these old files from building up we could do it manually, but that’s too time consuming and another thing to worry about in your already hectic life. Let’s look at how we could set up an automatic PHP script to do this for us.
Below is a basic snippet that will delete files older than 7 days old:

  1. $days = 7;  
  2. $path = './logs/';  
  3.   
  4. // Open the directory  
  5. if ($handle = opendir($path))  
  6. {  
  7.     // Loop through the directory  
  8.     while (false !== ($file = readdir($handle)))  
  9.     {  
  10.         // Check the file we're doing is actually a file  
  11.         if (is_file($path.$file))  
  12.         {  
  13.             // Check if the file is older than X days old  
  14.             if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )  
  15.             {  
  16.                 // Do the deletion  
  17.                 unlink($path.$file);  
  18.             }  
  19.         }  
  20.     }  
  21. }  
Note: filemtime() is a PHP function that returns a unix timestamp of when the file's contents were last changed.
Simple enough right? Now... what about if we only want to delete certain files? For example, we might only want to delete PDF files and leave everything else alone. Let's take the example above and modify it to our needs:

  1. $days = 7;  
  2. $path = './logs/';  
  3. $filetypes_to_delete = array("pdf");  
  4.   
  5. // Open the directory  
  6. if ($handle = opendir($path))  
  7. {  
  8.     // Loop through the directory  
  9.     while (false !== ($file = readdir($handle)))  
  10.     {  
  11.         // Check the file we're doing is actually a file  
  12.         if (is_file($path.$file))  
  13.         {  
  14.             $file_info = pathinfo($path.$file);  
  15.             if (isset($file_info['extension']) && in_array(strtolower($file_info['extension']), $filetypes_to_delete))  
  16.             {  
  17.                 // Check if the file is older than X days old  
  18.                 if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )  
  19.                 {  
  20.                     // Do the deletion  
  21.                     unlink($path.$file);  
  22.                 }  
  23.             }  
  24.         }  
  25.     }  
  26. }  
Again, relatively straightforward. All we've done different is setup an array of filetypes to delete on line 3, then get the file extension and check it's within this array (lines 14 and 15).

0 comments:

Post a Comment