Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to delete all files older than 2 days in PHP

Tags:

file

php

caching

Just curious

        $files = glob(cacheme_directory()."*");         foreach($files as $file)         {             $filemtime=filemtime ($file);             if (time()-$filemtime>= 172800)             {                 unlink($file);             }         } 

I just want to make sure if the code is correct or not. Thanks.

like image 822
user4951 Avatar asked Jan 22 '12 23:01

user4951


People also ask

What is the PHP command for deleting a file?

Description ¶ There is no delete keyword or function in the PHP language. If you arrived at this page seeking to delete a file, try unlink(). To delete a variable from the local scope, check out unset().


1 Answers

You should add an is_file() check, because PHP normally lists . and .., as well as sub-directories that could reside in the the directory you're checking.

Also, as this answer suggests, you should replace the pre-calculated seconds with a more expressive notation.

<?php   $files = glob(cacheme_directory()."*");   $now   = time();    foreach ($files as $file) {     if (is_file($file)) {       if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days         unlink($file);       }     }   } ?> 

Alternatively you could also use the DirectoryIterator, as shown in this answer. In this simple case it doesn't really offer any advantages, but it would be OOP way.

like image 67
buschtoens Avatar answered Sep 20 '22 09:09

buschtoens