简体   繁体   English

PHP,删除特定目录中具有特定扩展名的文件,只要超过(10)分钟

[英]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.我正在尝试创建一个 PHP 脚本,它基本上在目录的文件中查找具有特定文件扩展名的文件(它们都有唯一生成的文件名)获取具有该文件扩展名的文件的最后修改时间,然后如果超过 10 分钟,则删除这些文件。

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.我有一些类似的东西,它检查一个目录,但它查看每个文件,如果该文件早于 x 时间(20 秒来测试它是否有效),它会删除该文件。 Issue is it deletes files like .htaccess which I need.问题是它删除了我需要的文件,如 .htaccess。
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?这基本上只是删除了该目录中超过 20 秒的所有内容,但是无论如何都可以按文件扩展名进行过滤,以便 .htaccess 或其他文件扩展名之类的文件不会与要删除的文件一起被删除?

Technically filemtime is checking when the file was last modified , not created, so you could actually use find to duplicate that exact behavior:从技术上讲, filemtime正在检查文件的最后修改时间,而不是创建时间,因此您实际上可以使用find来复制该确切行为:

$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.不幸的是, find无法检查文件的确切创建时间,但无论如何您现在都不会查看它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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