views:

140

answers:

4

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.

+3  A: 

You would have to:

  • list all existing PHP files by traversing your directory structure
  • access their creation time with filectime
  • choose the three most recent ones in that list

This can get slow if you have a lot of files to search through. A database would be faster.

Victor Nicollet
+3  A: 

If you can prefix your filenames with the date and time (YYYY-MM-DD HH:mm:ss) then you can simply sort them alphabetically and take the last three. Otherwise, Victor has a great answer.

Scott Saunders
+1  A: 

You can get open a directory of files using opendir http://php.net/manual/en/function.opendir.php and readdir http://www.php.net/manual/en/function.readdir.php

You can then use the php function filemtime http://php.net/manual/en/function.filemtime.php which returns the last modify date of the filename passed into it.

So pretty much what you will do is look at all the files in the directory and order them by the return of filemtime (it returns a UNIX timestamp). Once you have them ordered (using any sort algoritm you like) just return the top 3 results.

danielrsmith
A: 

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.

menkes