Jump to content

PHP sort files in a folder by date - piz help!


luchosoto

Recommended Posts

Hi all!! I'm new to this forum.

 

I've got a bit of a problem. I found a script that reads files from a folder, and I modified it so that it can read image files and give extra info about them. It works very good, but it only sorts the files by alphabetical order; I want it to sort them by date as well. I've been tinkering with it, but all to no avail. I only got it to sort the files by reverse alphabetical order (rsort()). :'( :-\

 

Here's the whole script:

 

<?php

$folder = 'http/path/to/folder/';
$imgdir = 'absolute/path/to/folder';
$allowed_types = array('png','jpg','jpeg','gif');
$total_images = count(glob("$imgdir{*.gif,*.jpg,*.png, *.jpeg}", GLOB_BRACE));

?>

There are <?php echo $total_images;?> image(s) in the gallery.

<?php

$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
	$a_img[] = $imgfile;
	sort($a_img);
	reset($a_img);
} //end if
} //end while loop

$totimg = count($a_img);

for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
$img_width = ceil($size[0]);
$img_height = ceil($size[1]);

?>

<ul>
<li> File Name: <?php echo $a_img[$x];?> -- Dimensions: <?php echo $img_width. "x" .$img_height. " pixels";?> -- Date uploaded: <?php echo date ("d/n/Y, H:i:s", filemtime($imgdir.$a_img[$x]));?></li>
</ul>
<?php 

} //end for loop

?>

 

It looks like PHP, by default, sorts the files by name, doesn't it?

 

If someone could help me solve this problem (or tell me what's wrong with the script) I'd really appreciate it.

 

Thanks in advance!!!

I forgot to mention! I had tried that function already, but I don't know how to use it or where to place it. I had also tried with filectime() and many other functions, but since I'm kind of a newbie to php, I can't get them to work properly.

 

Any suggestions (or solutions) are kindly appreciated.

filemtime() returns the UNIX timestamp of a file, that's its age, in seconds, since (usually) midnight, Jan 1, 1970 UTC.  You could use the usort() function to sort your array with a callback function that uses filemtime to determine the age of the file.

 

function compare_by_age ($a,$b) {
if (filemtime($a) == filemtime($b)) return 0;
return (filemtime($a) < filemtime($b)) ? -1 : 1;
}

usort($filearray,"compare_by_age");


Untested

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.