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.
LVL 16
hankknightAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.