What is the best practice for moving files to a different directory based on their age in PHP?

When dealing with files in PHP, it can be useful to move files to a different directory based on their age. This can help with organizing and managing files, especially if you have a large number of them. One way to achieve this is by using PHP's filemtime function to get the last modification time of a file and comparing it to a specified threshold. If the file is older than the threshold, you can then use the PHP function rename to move the file to a different directory.

<?php
$sourceDir = '/path/to/source/directory/';
$destinationDir = '/path/to/destination/directory/';
$threshold = time() - (60 * 60 * 24 * 30); // 30 days in seconds

$files = scandir($sourceDir);

foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        $filePath = $sourceDir . $file;
        
        if (filemtime($filePath) < $threshold) {
            $newFilePath = $destinationDir . $file;
            rename($filePath, $newFilePath);
            echo "Moved file $file to $destinationDir\n";
        }
    }
}
?>