3

I'm trying to create a cron job that will provide me with a list of files in a directory that have been created or modified in the last day. For the life of me I can't see what is wrong with the code snippet below. It produces nothing and I know that I've updated at least one file in the last 24 hours.

<?php

$dir = opendir(".");


clearstatcache();

while(false != ($file = readdir($dir)))
{

if ( substr($file,-4) == ".php" ) 
{
    //echo $file;
    //echo "<br>";

    $yesdate = date('d.m.Y',strtotime("-1 days"));

    if (date("d.m.Y", filemtime($file))==$yesdate)
    {

        echo $file;

    }
    }

}

?>
3
  • If you fix your indents it will make the source more readable. Commented Dec 9, 2017 at 21:30
  • Did any of the provided solutions worked? Commented Dec 10, 2017 at 9:19
  • Yes, yours was perfect, thank you (apologies for the late reply, I have only just got home) Commented Dec 10, 2017 at 15:18

2 Answers 2

6

If you want to get files edited in last 24 hours than you need to use >= instead of == and compare timestamp instead of dates, like:

$dir = opendir(".");
clearstatcache();
$yesdate = strtotime("-1 days");
while(false != ($file = readdir($dir)))
{
    if ( substr($file,-4) == ".php" ) 
    {
        if (filemtime($file) >= $yesdate)
        {
            echo $file;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You will only find the files updated yesterday. If you want the last 24 hours, you could subtract the filemtime(..) from the current time. You will find the difference in seconds:

$now = time(); //you should put this outside of the loop
if ($now - filemtime($file) < 24 * 60 * 60)
{   
   //do something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.