Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 411
  • Last Modified:

PHP: scandir() for new files

This returns ALL directories and files:
$files = scandir($baseDir);

Open in new window


I ONLY want directories and files where files have been modified within the past 24 hours.
0
hankknight
Asked:
hankknight
3 Solutions
 
EMB01Commented:
I tried this before, I think it only works on Windows server.  I don't think you can count on any specific method to work, but you can try this:

http://php.net/manual/en/function.filemtime.php

See this post on the same page:
<?php
function GetCorrectMTime($filePath)
{

    $time = filemtime($filePath);

    $isDST = (date('I', $time) == 1);
    $systemDST = (date('I') == 1);

    $adjustment = 0;

    if($isDST == false && $systemDST == true)
        $adjustment = 3600;
   
    else if($isDST == true && $systemDST == false)
        $adjustment = -3600;

    else
        $adjustment = 0;

    return ($time + $adjustment);
}
?>

Open in new window

Also, this post:
It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:
<?php

function getAllFiles($directory, $recursive = true) {
     $result = array();
     $handle =  opendir($directory);
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = $directory.$datei;
               if (is_dir($file)) {
                    if ($recursive) {
                         $result = array_merge($result, getAllFiles($file.'/'));
                    }
               } else {
                    $result[] = $file;
               }
          }
     }
     closedir($handle);
     return $result;
}

function getHighestFileTimestamp($directory, $recursive = true) {
     $allFiles = getAllFiles($directory, $recursive);
     $highestKnown = 0;
     foreach ($allFiles as $val) {
          $currentValue = filemtime($val);
          if ($currentValue > $highestKnown) $highestKnown = $currentValue;
     }
     return $highestKnown;
}

// Use example

echo 'The newest file has the time stamp:<br>';
echo date('Y-m-d H:i:s', getHighestFileTimestamp('../'));

?>

Open in new window

0
 
gr8gonzoConsultantCommented:
You'll need a custom function like this:

function getFilesLastModified($dir,$lastMod = 86400)
{
  $return = array();
  if($dh = opendir($dir))
  {
    while(($file = readdir($dh)) !== false)
    {
      // Skip "." and ".."
      if(($file == ".") || ($file == "..")) continue;

      $fullFile = $dir . "/" . $file;
      if((time() - filemtime($fullFile)) < $lastMod)
      {
        $return[] = $file;
      }
    }
    closedir($dh);
  }
  return $return;
}
0
 
Ray PaseurCommented:
Not a complete solution, but hopefully you can copy this code and cut out the parts you don't want.  This finds all the PDF files in a directory and sorts them in descending order.  You could easily get the DATETIME value for "now - 24 hours" and use it as a filter.
<?php // RAY_EE_RSS_news_index.php
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// THE NAME OF THE MESSAGE DIGEST FILE AND THE RSS FEED
$md5 = 'RAY_EE_RSS_monitor.txt';
$rss = 'RAY_EE_RSS_rssfeed.xml';

// THE PATH TO OUR CURRENT WORKING DIRECTORY
$dir = getcwd();

// APPEND A SLASH IF NEEDED
if ($dir[strlen($dir)-1] != DIRECTORY_SEPARATOR) $dir .= DIRECTORY_SEPARATOR;

// AGGREGATE THE DIRECTORY INFORMATION INTO AN ARRAY OF ARRAYS
if ($dh = opendir($dir))
{
    $dir_datas = array();
    while ($file_name = readdir($dh))
    {
        // WE ONLY WANT TO CONSIDER FILES NAMED LIKE *.PDF
        $ext = strtoupper(end(explode('.', $file_name)));
        if ($ext == 'PDF')
        {
            $my_name = $dir . $file_name;
            $my_data = array
            ( 'name' => $file_name
            , 'size' => filesize($my_name)
            , 'time' => date('c', filemtime($my_name))
            )
            ;
            $dir_datas[] = $my_data;
        }
    }
}

// IF NO PDFS
if (empty($dir_datas)) die();

// CALL THE FUNCTION TO SORT THE ARRAY BY THE filemtime()
usort($dir_datas, 'timesort');

// GET THE URL PATH
$poz = strrpos($_SERVER["PHP_SELF"], DIRECTORY_SEPARATOR);
$urp = substr($_SERVER["PHP_SELF"], 0, $poz) . DIRECTORY_SEPARATOR;

// CREATE LINKS TO EACH OF THE FILES
$out = NULL;
foreach ($dir_datas as $pdf)
{
    $out .= $pdf["time"];
    $out .= ' ';
    $out .= '<a title="New Window for the PDF document" target="pdf" href="'
    . $urp
    . $pdf["name"]
    . '">'
    . $pdf["name"]
    . '</a>'
    . ' '
    . showfilesize($pdf["size"])
    . '<br/>'
    . PHP_EOL
    ;
}

// GET THE CURRENT MESSAGE DIGEST
$md5 = $dir . $md5;
$old = @file_get_contents($md5);

// MAKE THE NEW MESSAGE DIGEST AND WRITE IT
$new = md5($out);
file_put_contents($md5, $new);

// IF THERE IS A CHANGE, CREATE A NEW RSS FEED
if ($old != $new)
{
    create_rss_feed($rss);
}

// CREATE AND DISPLAY THE VIEW OF THE DIRECTORY
$htm
= '<h1>'
. "PUBLICATIONS: "
. date('F j, Y')
. '</h1>'
. $out
. '<br/>'
. 'SUBSCRIBE VIA '
. '<a title="New Window for the RSS Feed" target="rss" href="'
. $rss
. '">RSS</a>'
. PHP_EOL;
;
echo $htm;
die();




// A USER SORT FUNCTION TO ORDER BY DATETIME DESCENDING (NEWEST ON TOP)
function timesort($a, $b, $key='time')
{
    if     ($a[$key] == $b[$key]) return 0;
    return ($a[$key] >  $b[$key]) ? -1 : 1;
}


// FUNCTION TO PRODUCE AN EASY-TO-READ DESCRIPTION OF THE SIZE OF A FILE
function showFileSize ($xb)
{
    $pb = 1024*1024*1024*1024*1024;
    $tb = 1024*1024*1024*1024;
    $gb = 1024*1024*1024;
    $mb = 1024*1024;
    $kb = 1024;
    if     ($xb >= $pb) { $text = number_format(($xb / $pb),3) . " Pb"; }
    elseif ($xb >= $tb) { $text = number_format(($xb / $tb),2) . " Tb"; }
    elseif ($xb >= $gb) { $text = number_format(($xb / $gb),1) . " Gb"; }
    elseif ($xb >= $mb) { $text = number_format(($xb / $mb),1) . " Mb"; }
    elseif ($xb >= $kb) { $text = number_format(($xb / $kb),0) . " Kb"; }
    elseif ($xb >= 0)   { $text = number_format( $xb       ,0) . " bytes"; }
    else                { $text = "0 bytes"; }
    return $text;
}


// FUNCTION TO CREATE AND WRITE THE RSS FEED
function create_rss_feed($filename)
{
    // SET SOME VARIABLES FOR THE FEED
    $pubdate = date('r');
    $link    = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    $host    = $_SERVER["HTTP_HOST"];
    $title   = 'New PDF online at ' . $link;

// THE RSS DECLARED IN HEREDOC SYNTAX
$rss = <<<RSS
<?xml version="1.0" ?>
<rss version="2.0">
<channel>
  <title>$title</title>
  <description>RSS Feed from $host</description>
  <link>http://$host</link>
  <pubDate>$pubdate</pubDate>
  <item>
    <title>$title</title>
    <description>$title</description>
    <link>http://$link</link>
    <pubDate>$pubdate</pubDate>
  </item>
</channel>
</rss>
RSS;

    // WRITE THE RSS FEED INTO THE DIRECTORY
    file_put_contents($filename, $rss);
}

Open in new window

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now