Read files in a directory sorted by creation date

5

I have the following code to include all the PHP files I find in a directory:

if (is_dir(CONF_REL_PATH_BANANAS)) {
  foreach (glob(CONF_REL_PATH_BANANAS.'/*.php') as $file) {
    require_once($file);
  }
}

When sending the files there, I was careful to create them in the order I wanted them to be uploaded, but the result is:

array(7) {
  [0]=>
  string(29) "caminho/para/bananas/campaign.php"
  [1]=>
  string(29) "caminho/para/bananas/contacts.php"
  [2]=>
  string(29) "caminho/para/bananas/homepage.php"    // este seria o primeiro
  [3]=>
  string(32) "caminho/para/bananas/participate.php"
  [4]=>
  string(29) "caminho/para/bananas/partners.php"
  [5]=>
  string(28) "caminho/para/bananas/picking.php"
  [6]=>
  string(28) "caminho/para/bananas/results.php"
}

That is, the files are listed alphabetically.

Known solution

If you manipulate the name of the files, the problem is solved easily:

array(7) {
  [0]=>
  string(31) "caminho/para/bananas/1_homepage.php"
  [1]=>
  string(31) "caminho/para/bananas/2_campaign.php"
  [2]=>
  string(34) "caminho/para/bananas/3_participate.php"
  [3]=>
  string(30) "caminho/para/bananas/4_picking.php"
  [4]=>
  string(31) "caminho/para/bananas/5_partners.php"
  [5]=>
  string(30) "caminho/para/bananas/6_results.php"
  [6]=>
  string(31) "caminho/para/bananas/7_contacts.php"
}

But this raises maintenance issues and future additions of new files.

Question

How can I read files in a directory getting them sorted by their creation date?

    
asked by anonymous 13.01.2014 / 21:19

1 answer

1

You will not be able to use the function scandir() directly, but this way:

$arquivos = glob('/pasta/*');
usort($arquivos, function($a, $b) {
    return filemtime($a) < filemtime($b);
});


//print_r($arquivos);
    
13.01.2014 / 22:07