Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function cleanCache($pathToCacheFolder = null, $notAccessedInXDays = null){
- // uncomment the next lines if you want to stop the command if parameters are null
- // without showing any error
- /*
- if ($pathToCacheFolder === null || $notAccessedInXDays == null) {
- return;
- }
- */
- // throw exception if dir doesn't exist
- if ( ! is_dir($pathToCacheFolder)) {
- // if you don't want to show an error if pathToCacheFolder doesn't exist
- // just replace the next line with "return;"
- throw new RuntimeException("Folder '${pathToCacheFolder}' doesn't exist");
- }
- // create our file iterator for the given path
- $iterator = new FileSystemIterator($pathToCacheFolder);
- // ignore . and ..
- $iterator->setFlags(FileSystemIterator::SKIP_DOTS|FileSystemIterator::CURRENT_AS_PATHNAME);
- foreach ($iterator as $file) {
- // current time
- $now = new DateTime();
- // set file modified datetime
- $filemtime = new DateTime();
- $filemtime->setTimestamp(filemtime($file));
- // diff those two
- $diff = $now->diff($filemtime);
- $ext = pathinfo($file, PATHINFO_EXTENSION);
- // if file extension is one of these
- // and file wasn't modified since $notAccessedInXDays
- if (in_array($ext, array('gif', 'jpg', 'png')) && $diff->format("a") > $notAccessedInXDays) {
- // delete it
- unlink($file);
- }
- }
- }
- // usage example
- // delete all jpg,png,gif files that weren't modified since 15 days
- // inside "cache" dir
- cleanCache('./cache', 15);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement