X时间后自动删除所有文件 [英] Auto delete all files after x-time

查看:165
本文介绍了X时间后自动删除所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在x时间后(假设24小时后)自动删除子目录下的所有文件-无需使用服务器或pl中的cronjob命令.仅使用PHP代码或不单击任何内容即可访问页面,并且命令自动运行,该怎么做.

How do you auto delete all files under a sub directory after x-time (let say after 24 hours) - without using a cronjob command from server or pl. How can you do this just using PHP code or by just visiting the page without clicking something and the command auto runs.

推荐答案

响应我的第一个答案的最后评论.我将编写代码示例,因此我创建了另一个答案,而不是再添加一个注释.

Response for last comment from my first answer. I'm going to write code sample, so I've created another answer instead of addition one more comment.

要删除具有自定义扩展名的文件,您必须实现代码:

To remove files with custom extension you have to implement code:

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

    while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.'/'.$file)) < 86400) {  // 86400 = 60*60*24
          if (preg_match('/\.txt$/i', $file)) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>

注释:1.本示例使用正则表达式/\.txt$/i,这意味着将仅删除扩展名为txt的文件. "$"符号表示文件名必须以字符串".txt"结尾.标志"i"表示比较不区分大小写.有关 preg_match()函数的更多信息.

Comment: 1. This example uses regular expression /\.txt$/i, which means, that only files with extension txt will be removed. '$' sign means, that filename has to be ended with string '.txt'. Flag 'i' indicates, that comparison will be case-insensitive. More about preg_match() function.

此外,您还可以使用 strripos()函数来搜索带有一定的扩展名.这是代码段:

Besides you can use strripos() function to search files with certain extension. Here is code snippet:

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

    while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.'/'.$file)) < 86400) {  // 86400 = 60*60*24
          if (strripos($file, '.txt') !== false) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>

评论:这个例子似乎更加明显. strripos()的结果也可以通过以下两个函数的组合来实现:strrpos(strtolower($file), '.txt'),但是恕我直言,在代码中使用较少的函数以使其更具可读性和较小性是一个好规则.请仔细阅读strripos()函数(返回值块)页面上的警告.

Comment: This example seems more obvious. Result of strripos() also can be achieved with a combining of two functions: strrpos(strtolower($file), '.txt'), but, IMHO, it's a good rule to use less functions in your code to make it more readable and smaller. Please, read attentively warning on the page of strripos() function(return values block).

另一个重要提示:如果您使用的是UNIX系统,则由于文件许可权而导致文件删除失败.您可以查看有关 chmod()函数的手册.

One more important notice: if you're using UNIX system, file removing could fail because of file permissions. You can check manual about chmod() function.

祝你好运.

这篇关于X时间后自动删除所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆