• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

Seeking PHP script that lists all files within a directory tree that have been modified in the last 5 days

I'm looking to implement a very simple version control system for an a PHP-based web app that I manage, and was wondering how I might write a PHP routine that lists all files that are within a specific directory tree (including files that are contained within subdirectories, etc) which have been modified in the last 5 days.  Please advise.

Thanks,
- Yvan
0
egoselfaxis
Asked:
egoselfaxis
  • 3
  • 3
  • 3
  • +2
1 Solution
 
themrrobertCommented:
Here is a script that gets files in a directory with the time built into the function, you can modify it however you want.

Note that depending on which directory you are scanning, you may need to prepend the directory to the filename like this:

if(filemtime($directory . $file)
or
if(filemtime($directory . '/' . $file)

depending on how the directory is passed.
<?php

  function getDirectoryList ($directory) 
  {

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // open directory and walk through the filenames
    while ($file = readdir($handler)) {

      // if file isn't this directory or its parent, add it to the results
      if ($file != "." && $file != "..") {
        if(filemtime($file) <  (60*60*24*7)   // 7 days. change as needed
		$results[] = $file;
      }

    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

  }

?>

Open in new window

0
 
themrrobertCommented:
oops sorrry, you need to change line 17 to this:

if((filemtime($file) -time()) <  (60*60*24*7))

Complete code:
<?php

  function getDirectoryList ($directory) 
  {

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // open directory and walk through the filenames
    while ($file = readdir($handler)) {

      // if file isn't this directory or its parent, add it to the results
      if ($file != "." && $file != "..") {
        if((filemtime($file) -time()) <  (60*60*24*7))   // 7 days. change as needed
		$results[] = $file;
      }

    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

  }

?>

Open in new window

0
 
themrrobertCommented:
if( (time() - filemtime($file) ) <  (60*60*24*5) )

a new new line 17, sorry it must be an unlucky number for me today :D

this code will produce the result expected
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
xtermCommented:
The author asked for a recursive search, and I believe themrrobert's solution looks to only be for a single directory.  You could loop chdirs to fix this, but I think a shell exec is far simpler.  Try this and let me know if you'd like me to explain any part of it.


$filedir="/path/to/mysearchdir";

$files=exec("find $filedir 2>&1", $filelist, $retval);
for($i=0; $i<sizeof($filelist); $i++) {
        if((date("U")-filemtime($filelist[$i]))<432000) {
                echo "$filelist[$i]<br>";
        }
}

Open in new window

0
 
egoselfaxisAuthor Commented:
xterm - your script doesn't seem to  work on my server (might be a shared hosting based restriction)

- yg
0
 
xtermCommented:
Can you add the following to the top of the script and then paste whatever errors/output you get please?
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL | E_STRICT);

Open in new window

0
 
Beverley PortlockCommented:
The attached code should do what you want. Change the folder path in the example below and give it a go

<?php


     function searchDir( $pathToDirectory ) {

          $results = "";
          $fiveDaysAgo = strtotime("NOW -5 DAYS");

          // Make sure the directory has a trailing slash
          //
          if ( substr( $pathToDirectory, -1, 1 ) != "/" )
               $pathToDirectory .= "/";

          // Get list of files in directory
          //
          if ( $fileList = opendir( $pathToDirectory ) ) {
               while ( $aFile = readdir( $fileList ) ) {

                    if ( $aFile == "." || $aFile == ".." )
                         continue;

                    // if a directory is encountered then process it first
                    //
                    if ( @filetype( $pathToDirectory . $aFile ) == "dir" )
                         $results .= searchDir( $pathToDirectory . $aFile, $searchText );

                    if ( @filetype( $pathToDirectory . $aFile ) != "file" )
                         continue;

                    // Check date on file
                    //
                    $modTime = filemtime( $pathToDirectory . $aFile );

                    if ( $modTime >= $fiveDaysAgo )  {
                         // Found one!
                         //
                         $results .= $pathToDirectory . $aFile . ";";
                    }
               }

               closedir( $fileList );
          }

          return $results;
     }


$t = searchDir("/path/to/folder/" );
$arr = explode (";", $t );

echo "<pre>";
print_r( $arr );
echo "</pre>";

Open in new window

0
 
hernst42Commented:
Example using SPl objects from PHP 5.2
<?php

class fileModifiedIterator extends FilterIterator
{
    protected $modifiedAfter;

    public function __construct($directory, $days)
    {
        parent::__construct(
            new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($directory, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)
            ));
        $this->modifiedAfter = time() - 24 * 60 * 60 * $days;
    }

    public function accept()
    {
        $fileinfo = $this->current();
        return $fileinfo->getMtime() > $this->modifiedAfter;
    }
}

foreach (new fileModifiedIterator($directory, 5) as $fileInfo) {
    echo $fileInfo->getPathname() . PHP_EOL;
}

Open in new window

0
 
Beverley PortlockCommented:
Minor correction

<?php


     function searchDir( $pathToDirectory ) {

          $results = "";
          $fiveDaysAgo = strtotime("NOW -5 DAYS");

          // Make sure the directory has a trailing slash
          //
          if ( substr( $pathToDirectory, -1, 1 ) != "/" )
               $pathToDirectory .= "/";

          // Get list of files in directory
          //
          if ( $fileList = opendir( $pathToDirectory ) ) {
               while ( $aFile = readdir( $fileList ) ) {

                    if ( $aFile == "." || $aFile == ".." )
                         continue;

                    // if a directory is encountered then process it first
                    //
                    if ( @filetype( $pathToDirectory . $aFile ) == "dir" )
                         $results .= searchDir( $pathToDirectory . $aFile );

                    if ( @filetype( $pathToDirectory . $aFile ) != "file" )
                         continue;

                    // Check date on file
                    //
                    $modTime = filemtime( $pathToDirectory . $aFile );

                    if ( $modTime >= $fiveDaysAgo )  {
                         // Found one!
                         //
                         $results .= $pathToDirectory . $aFile . ";";
                    }
               }

               closedir( $fileList );
          }

          return $results;
     }


$t = searchDir("/path/to/folder/" );
$arr = explode (";", $t );

echo "<pre>";
print_r( $arr );
echo "</pre>";

Open in new window

0
 
egoselfaxisAuthor Commented:
xterm -- here is the output:


Notice: Undefined variable: filelist in D:\Inetpub\staging\version.php on line 44

Notice: Undefined variable: retval in D:\Inetpub\staging\version.php on line 44

Warning: exec() has been disabled for security reasons in D:\Inetpub\staging\version.php on line 44

Notice: Undefined variable: filelist in D:\Inetpub\staging\version.php on line 45
0
 
egoselfaxisAuthor Commented:
Works great - thanks!
- Yvan
0
 
xtermCommented:
Ah, yeah, your system is locked down from exec() commands - that's cool, bportlock's solution is a nice one too.
0
 
Beverley PortlockCommented:
You're welcome. Thanks for the points.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 3
  • 3
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now