简体   繁体   中英

PHP, delete files in a specific directory with a specific extension as long as it's over (10) minutes old

I'm trying to create a PHP script that basically looks through the files of a directory for files with a certain file extension, (they all have uniquely generated files names) get the time it was last modified for the files with that file extension, and then if it's older than 10 minutes, to delete those file.

I have something that kind of works, it checks through a directory but it looks through every file and if that file is older than x amount of time (20 seconds to test if it works) it'll delete the file. Issue is it deletes files like .htaccess which I need.
This is what I have currently:

<?php
$path = './test/';
if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) { 
        $filelastmodified = filemtime($path . $file);
        if((time() - $filelastmodified) > 20) //20 seconds
        {
           unlink($path . $file);
        }

    }

    closedir($handle); 
}
?>

That basically just deletes everything in that directory so long it's over than 20 seconds, but is there anyway to filter by file extensions so that files like .htaccess or other file extensions don't get deleted along with the files meant to be deleted?

Technically filemtime is checking when the file was last modified , not created, so you could actually use find to duplicate that exact behavior:

$path = "/path/to/dir";
$extention = "whatever";
$ret = shell_exec("find {$path} -type f -name '*.{$extention}' -mmin +10 -exec rm -f {} \;");
//Equal to
//$ret = shell_exec("find {$path} -type f -name '*.{$extention}' -mmin +10 -delete");

Unfortunately find doesn't have the ability to check for when the file was exactly created, but then again you're not looking at that now anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM