Jump to content

use PHP to sort file in a directory by last modified


woocha

Recommended Posts

OK I know the basics, I think?....I know I will need to use opendir() sort() and filemtime()....but I can even begin to get how they will work together..In truth this problem might be a bit over my head, but I really want to give it a shot, so any help would be greatly appreciated.

 

I want to sort the files in a given directory by the date they were last modified.

I think this is possible, but I have talked to anyone who has done it yet, so if anyone could help me out, that woiuld be great.

Thanks

Access time and mod time are different....  Also, what if by some weird chance, the time on two files is the same?

 

I would do this:

 

$files = array();
if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
             $files[$file] = filemtime($file);
        }
    closedir($dh);
}

asort($files);
print_r($files);

 

The only problem with that is that the file names could be messed up if they aren't value for a PHP array key....

 

You could work around that by creating a second array of names though, and map them by IDs.....

Access time and mod time are different....  Also, what if by some weird chance, the time on two files is the same?

 

I would do this:

 

$files = array();
if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
             $files[$file] = filemtime($file);
        }
    closedir($dh);
}

asort($files);
print_r($files);

 

The only problem with that is that the file names could be messed up if they aren't value for a PHP array key....

 

You could work around that by creating a second array of names though, and map them by IDs.....

 

 

Thank you...I will test it, but it that really all there is to it?...I thought there would have to so much more.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.