php x 时间后自动删除所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1921466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:19:12  来源:igfitidea点击:

Auto delete all files after x-time

phpfiledelete-file

提问by jones

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.

如何在 x 时间后(假设 24 小时后)自动删除子目录下的所有文件 - 不使用来自服务器或 pl 的 cronjob 命令。如何仅使用 PHP 代码或仅访问页面而不单击某些内容并且命令自动运行来执行此操作。

回答by Alex

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);
          }
        }
    }
  }
?>

Comment: 1. This example uses regular expression /\.txt$/i, which means, that only files with extension txtwill 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.

评论: 1. 本例使用正则表达式/\.txt$/i,即只txt删除带扩展名的文件。'$' 符号表示文件名必须以字符串 '.txt' 结尾。标志 'i' 表示比较将不区分大小写。有关preg_match()函数的更多信息。

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

此外,您可以使用strripos()函数搜索具有特定扩展名的文件。这是代码片段:

<?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);
          }
        }
    }
  }
?>

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).

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

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.

一个更重要的注意事项:如果您使用的是 UNIX 系统,文件删除可能会因为文件权限而失败。您可以查看有关chmod()函数的手册。

Good luck.

祝你好运。

回答by Alex

You can use PHP core functions filectime()and unlink()to check time of file creation and delete its file/files.

您可以使用 PHP 核心函数filectime()unlink()来检查文件创建时间并删除其文件/文件。

EDIT. Code example:

编辑。 代码示例:

  if ($handle = opendir('/path/to/files')) {

    while (false !== ($file = readdir($handle))) {
        if (filectime($file)< (time()-86400)) {  // 86400 = 60*60*24
          unlink($file);
        }
    }
  }

回答by Raymond

Well here we go, the PHP script that deletes the files that is X number of days old.

好吧,我们开始了,删除 X 天前的文件的 PHP 脚本。

<?
$days = 1;
$dir = dirname ( __FILE__ );

$nofiles = 0;

    if ($handle = opendir($dir)) {
    while (( $file = readdir($handle)) !== false ) {
        if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
            continue;
        }

        if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
        }
    }
    closedir($handle);
    echo "Total files deleted: $nofiles \n";
}
?>

Now paste this code and save it as a php file, upload it to the folder from where you want to delete the files. You can see at the beginning of this php code

现在粘贴此代码并将其另存为 php 文件,将其上传到要从中删除文件的文件夹。你可以在这段php代码的开头看到

$days = 1;

that sets the number of days, for example if you set it to 2 then files older than 2 days will be deleted. Basically this is what happens when you run the script, gets the current directory and reads the file entries, skips ‘.' for current directory and further checks if there are any other directories,

设置天数,例如,如果您将其设置为 2,那么早于 2 天的文件将被删除。基本上这就是当您运行脚本、获取当前目录并读取文件条目、跳过 '.' 时会发生的情况。对于当前目录并进一步检查是否还有其他目录,

if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
           continue;
}

if the file entry is not a directory then it fetches the file modified time (last modified time) and compares, if it is number of days old

如果文件条目不是目录,则它获取文件修改时间(上次修改时间)并进行比较,如果它是旧的天数

if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
}

if the condition becomes true then it deletes the file with the help of unlink( ) php function. Finally closes the directory and exits. I have also added a counter to count the number of files being deleted, which will be displayed at the end of deletion process. So place the php file in the directory that needs the file deletion and execute it.

如果条件成立,那么它会在 unlink() php 函数的帮助下删除文件。最后关闭目录并退出。我还添加了一个计数器来计算被删除的文件数,它将在删除过程结束时显示。所以把php文件放在需要删除文件的目录下执行。

Hopefully that helps :)

希望这有帮助:)

回答by ssmithereens

After trying to use these examples, I hit a couple of issues:

在尝试使用这些示例后,我遇到了几个问题:

  1. The comparison operator should be greater than, not less than
  2. filemtime returns the modified time. filectime is the time when a file's inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated, which may lead to unexpected results
  1. 比较运算符应大于,不小于
  2. filemtime 返回修改时间。filectime 是文件的 inode 数据更改的时间;也就是说,当 inode 中的权限、所有者、组或其他元数据更新时,可能会导致意外结果

I changed the example to use filemtime and fixed the comparison as follows:

我将示例更改为使用 filemtime 并将比较修复如下:

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

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

回答by AdRock

Here is another example that uses GLOB and it will delete any file

这是另一个使用 GLOB 的示例,它将删除任何文件

$files = glob('path/to/your/files/*');

foreach($files as $file) { // iterate files
    // if file creation time is more than 5 minutes
    if ((time() - filectime($file)) > 3600) {  // 86400 = 60*60*24
        unlink($file);
    }
}

or if you want to exclude certain files

或者如果您想排除某些文件

$files = preg_grep('#\.txt#', glob('/path/to/your/files/*'), PREG_GREP_INVERT);

回答by user2629005

$path = 'folder/subfolder/';

/* foreach (glob($path.'.txt') as $file) { */
foreach (glob($path.'*') as $file) {

    if(time() - filectime($file) > 86400){
      unlink($file);
    }
}

回答by Stergios Zg.

function deleteCachedData($hours=24)
{
    $files = glob(ROOTDIR.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'*.txt');
    foreach($files as $file) {
        if(is_file($file) && (time() - filectime($file)) > $hours*3600) {
            unlink($file);
        }
    }

}

}

回答by pwr

I use shell AT command, it's like a cronjob though

我使用 shell AT 命令,虽然它就像一个 cronjob

php:

php:

exec("echo rm /somedir/somefile.ext|at now +24 hours");