PHP:清除 cron 临时文件的好脚本?

发布于 2024-09-16 03:00:07 字数 147 浏览 7 评论 0原文

我有一个由我的业务应用程序生成的临时文件夹,并且希望其中的文档只能在大约 30 分钟内可用。我很想建立一个索引来跟踪每个文件的创建时间,但这对于临时文件来说有点愚蠢,它们不太重要,但我希望根据上次修改的时间删除它们。

我需要对我的 Linux 服务器执行什么操作?

I have a temporary folder generated by my business application and wish for the documents within to be only available for around 30 minutes. I was tempted to build an index to keep track of when each file was created but that would be a little silly for just temporary files, they are not of too much importance but I would like them to removed according to the time they were last modified.

What would I need to do this with my Linux server?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕头说它不想醒 2024-09-23 03:00:15

您只需要对文件调用 stat 并决定是否取消链接< /code> 他们或不基于他们的mtime

每隔十分钟左右从 cron 或 anacron 调用此脚本。

或者您可以使用 tmpwatch,这是一个为此目的设计的程序。

You'd need nothing more than to call stat on the files and decide whether to unlink them or not based on their mtime.

Call this script every ten minutes or so from cron or anacron.

Or you could use tmpwatch, a program designed for this purpose.

伪装你 2024-09-23 03:00:14

函数 filemtime() 将允许您检查文件的最后修改日期。您需要做的是每分钟运行您的 cron 作业并检查它是否大于阈值,并根据需要 unlink() 它。

$time = 30; //in minutes, time until file deletion threshold
foreach (glob("app/temp/*.tmp") as $filename) {
    if (file_exists($filename)) {
        if(time() - filemtime($filename) > $time * 60) {
            unlink($filename);
        }
    }
}  

这应该是您所要求的最有效的方法,如果在有很多文件的情况下需要较低的准确性,请将 cron 阈值更改为 10 分钟。

The function filemtime() will allow you to check the last modify date of a file. What you will need to do is run your cron job each minute and check if it is greater than the threshold and unlink() it as needed.

$time = 30; //in minutes, time until file deletion threshold
foreach (glob("app/temp/*.tmp") as $filename) {
    if (file_exists($filename)) {
        if(time() - filemtime($filename) > $time * 60) {
            unlink($filename);
        }
    }
}  

This should be the most efficient method as you requested, change the cron threshold to 10 minutes if you need a less accuracy in case there are many files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文