root root - 10 months ago 32
PHP Question

Do not delete files that are younger than 1 hour

I want to check a folder on my server for files that are older than an hour old every 30 minutes, so I set up a cronjob to do that. As I am fairly new to php I had to browse a bit to find a solution that does not delete my parent/target directory and I found one!

function deleteContent($path){
$iterator = new DirectoryIterator($path);
foreach ( $iterator as $fileinfo ) {
if((time()-filectime($fileinfo->getPathname())) < 600 )
if((time()-filectime($fileinfo->getPathname())) < 600 )
} catch ( Exception $e ){
// write log
return false;
return true;

Notice that the
if((time()-filectime($fileinfo->getPathname())) < 600 )
was my approach of finding a solution to my time problem.

The script should not delete folders or files that are younger than 1 Hour so I took the time we have now and subtracted it by the time, that the file/folder was changed the last time and compared it to 600 seconds (10 Minutes) just for testing purposes.

Sadly the script still deletes every file no matter when it was created.

Am I doing something wrong or does anybody has another approach?



sometimes calling the underlying OS's functions is the better approach

exec('find /var/www/html/downloads/ -type f -mmin +60 -exec rm {} \;');

php function to run the cli command find, which finds the files in the path specified, of the type f(for file) with a file time greater than 60 minutes old, then exec(run) rm which is linux remove(delete)