简体   繁体   English

使用PHP递归列出所有带日期的文件

[英]List all files with dates recursively with PHP

Before someone marks this duplicate, please understand that I searched this site, Google searches, and PHP.net. 在有人标记此副本之前,请理解我搜索了此网站,Google搜索和PHP.net。

What I want is super simple. 我想要的是超级简单。 I want a list of all files on a website with a datestamp (last modified). 我想要一个带有日期戳(最后修改)的网站上所有文件的列表。 I have found several scripts that claim to do this, but none of them are working. 我发现有几个声称可以执行此操作的脚本,但它们都没有工作。

The best one I have found so far is this one: 到目前为止我发现的最好的是这一个:

header("Pragma: public");
  header("Cache-Control: private");
  header("Content-Type: text/csv");
  header("Content-Disposition: attachment; filename=age-of-files.csv");

  $result = array();
  $handle =  opendir(".");
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = "./".$datei;
               if (!is_dir($file))
                    $result[] = $file;
          }
     }
     closedir($handle);
  foreach($result as $r)
    if (file_exists($r))
      echo substr($r,2).",".date ("m-d-Y", filemtime($r))."\r\n"; 

This works great for the dircetory the script is run in, but it is not recursive. 这适用于脚本运行的dircetory,但它不是递归的。 I need it to keep going for every sub directory. 我需要它继续为每个子目录。 My goal is to have a sortable list so I can find files that were modified on or around certain dates. 我的目标是有一个可排序的列表,以便我可以找到在某些日期或周围修改过的文件。

I am new to PHP, so bear with me. 我是PHP的新手,所以请耐心等待。 I did some research at PHP.net (I keep seeing people refer to SPL and I'm not sure what that stands for or what it is, but perhaps it is a group of standard PHP classes?), and it looks like I need to be using RecursiveDirectoryIterator somehow. 我在PHP.net做了一些研究(我一直看到人们提到SPL,我不确定它代表什么或它是什么,但也许它是一组标准的PHP类?),看起来我需要以某种方式使用RecursiveDirectoryIterator。

I found this script that looks great on paper, but running it on my site gives a blank white screen. 我发现这个脚本在纸上看起来很棒,但在我的网站上运行会给出一个空白的白色屏幕。

try
{
        /*** freds home directory ***/
        $rdi = new recursiveDirectoryIterator('/',  FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS);
        $it = new recursiveIteratorIterator( $rdi );
        while( $it->valid())
        {
                if( !$it->isDir() )
                {
                        echo $it->current().' '.date('Y m d H:i:s', $it->getATime() )."\n";
                }

                /*** move to the next element ***/
                $it->next();
        }
}
catch(Exception $e)
{
        /*** echo the error message ***/
        echo $e->getMessage();
}

I would prefer to use the first script as I like that it creates a csv file (easy to sort), but I am not sure how to reconcile the two. 我更喜欢使用第一个脚本,因为它创建了一个csv文件(易于排序),但我不确定如何协调这两个。 Can someone advise me on how to incorporate RDI into the first script? 有人可以告诉我如何将RDI合并到第一个脚本中吗?

Here is a little code that I found working very well 这是一个我发现工作得非常好的小代码

$rdi = new RecursiveDirectoryIterator("path/"); // The directory here
$rii = new RecursiveIteratorIterator($rdi);

foreach ($rii as $filename=>$cur) {
    echo $cur.' '.date('Y m d H:i:s', $cur->getATime() )."<br/>";
}

Try something like this, which is similar to the second example that you provided: 尝试这样的东西,这与你提供的第二个例子类似:

<?php

$path = __DIR__;

if (!is_dir($path)) {
    throw new RuntimeException(sprintf('Path %s does not exist!', $path));
}

if (!is_readable($path)) {
    throw new RuntimeException(sprintf('Path %s is not readable!', $path));
}

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path)
);

$files = [];

foreach ($iterator as $fileInfo) {
    if ($fileInfo->isFile()) {
        $files[] = [
            $fileInfo->getFilename(),
            dirname($fileInfo->getPathname()),
            date('c', $fileInfo->getMTime())
        ];
    }
}

print_r($files);

Given an example file structure: 给出一个示例文件结构:

在此输入图像描述

This yields: 这会产生:

Array
(
    [0] => Array
        (
            [0] => .DS_Store
            [1] => /private/tmp/rec
            [2] => 2015-08-08T08:28:33+00:00
        )

    [1] => Array
        (
            [0] => .DS_Store
            [1] => /private/tmp/rec/0
            [2] => 2015-08-08T08:28:33+00:00
        )

    [2] => Array
        (
            [0] => 0.1.txt
            [1] => /private/tmp/rec/0/0.1
            [2] => 2015-08-08T08:27:58+00:00
        )

    [3] => Array
        (
            [0] => 0.txt
            [1] => /private/tmp/rec/0
            [2] => 2015-08-08T08:27:58+00:00
        )

    [4] => Array
        (
            [0] => .DS_Store
            [1] => /private/tmp/rec/1
            [2] => 2015-08-08T08:28:33+00:00
        )

    [5] => Array
        (
            [0] => .DS_Store
            [1] => /private/tmp/rec/1/1.1
            [2] => 2015-08-08T08:28:27+00:00
        )

    [6] => Array
        (
            [0] => 1.1.txt
            [1] => /private/tmp/rec/1/1.1
            [2] => 2015-08-08T08:27:58+00:00
        )

    [7] => Array
        (
            [0] => 1.txt
            [1] => /private/tmp/rec/1
            [2] => 2015-08-08T08:27:58+00:00
        )

    [8] => Array
        (
            [0] => rec.php
            [1] => /private/tmp/rec
            [2] => 2015-08-08T08:48:30+00:00
        )

)

Each match is stored as a sub-array element containing: 每个匹配都存储为子数组元素,包含:

  1. Filename 文件名
  2. Current dirpath 目前的dirpath
  3. Datetime of last modification 上次修改的日期时间

It makes some additional checks to ensure that the $path provided can be read. 它进行了一些额外的检查,以确保可以读取提供的$path

You now have a result set of $files in an array, you should be able to reuse some of the code in your first example to output as a .csv file. 您现在在数组中有$files的结果集,您应该能够重用第一个示例中的一些代码作为.csv文件输出。

Hope this helps :) 希望这可以帮助 :)

If anyone is curious, this is what I ended up with. 如果有人好奇,这就是我最终的结果。 It combines the simplicity and effectiveness of the first answer with the csv of the first example in my question. 它将第一个答案的简单性和有效性与我问题中第一个例子的csv结合起来。 When I open the csv file in excel, I am able to sort by day easily. 当我在excel中打开csv文件时,我可以轻松地按日排序。

The reason I needed this was to help track down some malware on one of my sites. 我需要这个的原因是为了帮助追踪我的一个网站上的一些恶意软件。 By having a list of all the files, I can sort by date and look for files that were added on suspicious dates. 通过列出所有文件,我可以按日期排序并查找在可疑日期添加的文件。 Or conversely, if I found a known threat on a certain day, I can easily see what other files were modified on that day/time. 或者相反,如果我在某一天发现了已知威胁,我可以很容易地看到当天/时间修改了哪些其他文件。 It helped me immensely in finally ridding my site of the persistent infection. 它帮助我极大地消除了我的网站持续感染。 It kept coming back to life because I wasn't able to remove all the files. 它不断恢复生机,因为我无法删除所有文件。 Using this simple script, I finally found the backdoor shell that had been installed. 使用这个简单的脚本,我终于找到了已经安装的后门shell。 Phew! 唷!

Thanks so much to both answerers! 非常感谢两位回答者! :) :)

<?php
header("Pragma: public");
header("Cache-Control: private");
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=age-of-files.csv");

$rdi = new RecursiveDirectoryIterator("."); // The directory here
$rii = new RecursiveIteratorIterator($rdi);

foreach ($rii as $filename=>$cur) {
    echo $cur.', '.date('m-d-Y', $cur->getATime() ).', '.date('H:i:s', $cur->getATime() )."\r\n";
}
?>

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

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