2

I'm trying to make a sort of blog with php and I want to include the 5 newest files in an other directory by modification time.

I can inculde them all one by one each time I have made a new file, but it would be nice if I can just include the newest 5.

Because i don't want to put the modification date in the file name I really don't know how to do it.

Is there a way to do that?

Moreno__R
  • 45
  • 6
  • Check out scandir() and filemtime(). http://php.net/manual/en/function.scandir.php http://php.net/manual/en/function.filemtime.php – Will Oct 09 '13 at 18:20
  • Do you really mean `include`, as in these are PHP files? If so, this sounds like you're mixing your content with your implementation. Maybe consider using a database of some sort... – IMSoP Oct 09 '13 at 18:23
  • @IMSoP I really mean include, I want them to be php files. It's not really a blog or something. It is actuallt for myself. I have a lot of websites (for school) and because I have a lot of files I just want the newest 5 so I can easely see with which site i'm busy. – Moreno__R Oct 09 '13 at 18:47

4 Answers4

0
$path = "/path/to/directory"; //the directory path 

$latest5files = array();    //array for latest 5 files to be stored

$d = dir($path);

while ((false !== ($entry = $d->read())) || count($latest5files) < 5) 
{
     $filepath = "{$path}/{$entry}";

     if ((is_file($filepath))) 
     {
         $latest_filename[] = $entry;
     }
}

Then include the whole files in the array

for ($i = 0; $i < count($latest5files); $i++)
{
    include $latest5files[ $i ];
}
zkanoca
  • 9,664
  • 9
  • 50
  • 94
  • now i have this and the directory i want it in is "sites", but it won't work. am i doing something wrong? `read())) || count($latest5files) < 5) { $filepath = "{$path}/{$entry}"; if ((is_file($filepath))) { $latest_filename[] = $entry; } } for ($i = 0; $i < count($latest5files); $i++) { include $latest5files[ $i ]; } ?>` – Moreno__R Oct 09 '13 at 18:59
  • @Moreno__R change `sites/` to `/sites`. Because script tries to find `sites//filename.txt` which is a non-existing url. – zkanoca Oct 09 '13 at 20:17
0

You can get list files with array for eg.

$a[1234567890] = 'file1.php';

arsort($a);

foreach(array_slice($input, 0, 5) as $fTime => $file):
0

http://php.net/manual/en/function.filemtime.php

http://php.net/manual/en/function.stat.php

You can check the file modification time with this functions.

Read the file sort it with that time.

More info on

Sorting files by creation/modification date in PHP

Community
  • 1
  • 1
anytimeIR
  • 1
  • 1
0

This would be a way to get last access info of all files in a directory

    $p = "path";


    $a = scandir($p);


    foreach($a as $f){

    $last_access = fileatime($p."/".$f);

    }
laxertu
  • 131
  • 3