开发者

PHP How to include files based on creation date?

开发者 https://www.devze.com 2022-12-14 21:17 出处:网络
I want to create a news page that includes a snippet of the latest 3 filea created in the following directory structure:

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-lates开发者_C百科t-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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消