Search code examples
phpdateincludecreationcode-snippets

PHP How to include files based on creation date?


I want to create a news page that includes a snippet of the latest 3 filea created in the following directory structure:

So lets say I have the following files:

/news.php /2010/the-latest-article.php /2009/some-long-article-name.php /2009/another-long-article-name.php /2009/too-old-article-name.php /2009/another-old-article-name.php

I only want to include the first 3 files into the news.php output.


Solution

  • From php.net:

    foreach (glob("../downloads/*") as $path) { //configure path
        $docs[filectime($path)] = $path;
    } ksort($docs); // sort by key (timestamp)
    
    foreach ($docs as $timestamp => $path) {
        print date("d. M. Y: ", $timestamp);
        print '<a href="'. $path .'">'. basename($path) .'</a><br />'; 
    }
    

    Also, filemtime may give better results if you are on windoze.