Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Sort images from Dir

Posted on 2009-02-11
11
Medium Priority
?
256 Views
Last Modified: 2013-12-12
Hey guys, I'm using a php script to read all images inside a dir and display the images on my clients webpage. Everything works fine but now he wants to sort the images.

He wants to sort from the most recent images to the oldest.

You can see an example right here:
http://www.giornate.com.br/new/clientes2.php?cli=25

<?php
 
// open the dir and read the images...
 
if ($handle = opendir('clientes/' . tiracento($nomecliente) . '/img/')) {
 
    while (false !== ($file = readdir($handle))) {
		
        // load just images
		
        if (strtolower(substr($file, -4, 4)) == '.jpg' || strtolower(substr($file, -4, 4)) ==
            '.gif' || strtolower(substr($file, -4, 4)) == '.png' || strtolower(substr($file,
            -5, 5)) == '.jpeg') {
 
            echo "<div class=\"panel\">";
            echo "<a href=\"clientes/" . tiracento($nomecliente) . "/img/" . $file .
                "\" rel=\"lytebox\" title=\"\">";
            echo "<img src=\"";
            echo resize("clientes/" . tiracento($nomecliente) . "/img/" . $file, array("h" =>
                66, "scale" => true));
            echo "\" hspace=\"2\" border=\"0\">";
			echo "</div>";
 
        }
 
    }  
 
} 
 
?>

Open in new window

0
Comment
Question by:fackz
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 19

Expert Comment

by:Michael701
ID: 23615694
I'd read the dir and create an array of date_created and file_name, then arsort the array by created_date

do you need code?
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 23615958
Try something along these lines. I have not tested it and you need to decide how you will know if it is to be sorted

<?php
 
// open the dir and read the images...
 
 
$imageNames = array();
 
if ($handle = opendir('clientes/' . tiracento($nomecliente) . '/img/')) {
 
    while (false !== ($file = readdir($handle))) {
                
        // load just images
                
        if (strtolower(substr($file, -4, 4)) == '.jpg' || strtolower(substr($file, -4, 4)) ==
            '.gif' || strtolower(substr($file, -4, 4)) == '.png' || strtolower(substr($file,
            -5, 5)) == '.jpeg') {
 
            $imageNames [] = $file;            
 
        }
 
    }  
 
 
    // depending on some paraneter or other variable, decide what sorting (if any)
    //
    if ( $sortOrder == "asc" )
        asort( $imageNames );
    else
       if ( $sortOrder == "desc" )
          arsort( $imageNames );
 
    // use the list to show the images
    //
    foreach( $imageName as $file ) {          
 
             echo "<div class=\"panel\">";
            echo "<a href=\"clientes/" . tiracento($nomecliente) . "/img/" . $file .
                "\" rel=\"lytebox\" title=\"\">";
            echo "<img src=\"";
            echo resize( $file, array("h" =>
                66, "scale" => true));
            echo resize("clientes/" . tiracento($nomecliente) . "/img/" . $file, array("h" =>
                66, "scale" => true));
            echo "\" hspace=\"2\" border=\"0\">";
                        echo "</div>";
     }
} 
 
?>

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 23618340
You can use stat() or filemtime() to determine the date of creation or modification.  Beware that some functions that read directories will "touch" the files, thus marking them all as "recently used" and rendering the algorithm you're trying to develop useless.

Good luck, ~Ray
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 19

Expert Comment

by:Michael701
ID: 23618643
Here's the code.

And Ray is right there are things that can mess up the created / modified date.

Anyway, this will display a table of the directory in REVERSE date order.

Note to get date order change arsort() to asort()
$path="images";
unset($array_list);
if ($handle = opendir($path)) 
{ 
  echo "<table>\n";
  while (false !== ($filename = readdir($handle))) 
  { 
    if ($filename != "." && $filename != "..") 
    {
      echo "<tr><td>".$filename."</td><td>".date ("F d Y H:i:s.", filemtime($path.'/'.$filename))."</td></tr>\n";
      $array_list[$filename]=filemtime($path.'/'.$filename);
    }
  } 
  echo "</table><br />\n";
  closedir($handle); 
  arsort($array_list);
 
  echo "<br />\n";
  echo "<table>\n";
  foreach ($array_list as $filename=>$mtime)
    echo "<tr><td>".$filename."</td><td>".date ("F d Y H:i:s.", $mtime)."</td></tr>\n";
  echo "</table><br />\n";
}

Open in new window

0
 

Author Comment

by:fackz
ID: 23621570
bportlock: I'm getting this error:

Warning: Invalid argument supplied
0
 

Author Comment

by:fackz
ID: 23621575
Michael, how should I use your code inside my code?
I'm a little confused...
0
 

Accepted Solution

by:
fackz earned 0 total points
ID: 23621934
The following function made my day
<?
 
function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
{
$files = scandir($dir);
 
$array = array();
 
foreach($files as $file)
{
	if($file != '.' && $file != '..')
	{
		$now = time();
		$last_modified = filemtime($dir.$file);
 
		$time_passed_array = array();
 
		$diff = $now - $last_modified;
 
		$days = floor($diff / (3600 * 24));
 
		if($days)
		{
		$time_passed_array['days'] = $days;
		}
 
		$diff = $diff - ($days * 3600 * 24);
 
		$hours = floor($diff / 3600);
 
		if($hours)
		{
		$time_passed_array['hours'] = $hours;
		}
 
		$diff = $diff - (3600 * $hours);
 
		$minutes = floor($diff / 60);
 
		if($minutes)
		{
		$time_passed_array['minutes'] = $minutes;
		}
 
		$seconds = $diff - ($minutes * 60);
 
		$time_passed_array['seconds'] = $seconds;
 
	$array[] = array('file'         => $file,
		             'timestamp'    => $last_modified,
		             'date'         => date ($date_format, $last_modified),
		             'time_passed'  => $time_passed_array);
	}
}
 
usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));
 
if($sort_type == 'descending')
{
krsort($array);
}
 
return array($array, $sort_type);
}
?>

Open in new window

0
 
LVL 19

Expert Comment

by:Michael701
ID: 23622064
my code was a working example. just take out the echo statements and use $array_list in your code
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 23622110
Just a thought going forward, any time you think you need to do a date / time calculation this way, you might want to take a step back and look at the functions strtotime() and date() and maybe occasionally mktime().  Not only are these faster than writing your own date / time manipulation, they are less prone to error.  HTH, ~Ray

$days = floor($diff / (3600 * 24));
if($days)
  {
     $time_passed_array['days'] = $days;
  }
0
 
LVL 3

Expert Comment

by:albrieu
ID: 23622637
try this
<?
 
function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
{
$files = scandir($dir);
 
$array = array();
 
foreach($files as $file)
{
        if($file != '.' && $file != '..')
        {
                $now = time();
                $last_modified = filemtime($dir.$file);
 
                $time_passed_array = array();
 
                $diff = $now - $last_modified;
 
                $days = floor($diff / (3600 * 24));
 
                if($days)
                {
                $time_passed_array['days'] = $days;
                }
 
                $diff = $diff - ($days * 3600 * 24);
 
                $hours = floor($diff / 3600);
 
                if($hours)
                {
                $time_passed_array['hours'] = $hours;
                }
 
                $diff = $diff - (3600 * $hours);
 
                $minutes = floor($diff / 60);
 
                if($minutes)
                {
                $time_passed_array['minutes'] = $minutes;
                }
 
                $seconds = $diff - ($minutes * 60);
 
                $time_passed_array['seconds'] = $seconds;
 
        $array[$file] = array('file'         => $file,
 
                             'timestamp'    => $last_modified,
                             'date'         => date ($date_format, $last_modified),
                             'time_passed'  => $time_passed_array);
        }
}
 
usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));
 
if($sort_type == 'descending')
{
krsort($array);
}
 
return array($array, $sort_type);
}
 
$_path='wordpress/wp-admin/images/';
// open the dir and read the images...
$_files=Sort_Directory_Files_By_Last_Modified($_path);
$files=$_files[0];
unset($_files);
if (count($files)>0 and is_array($files)) {
 
    foreach($files as $file)
     {           
        // load just images
        $path_parts = pathinfo($file['file']);		 
        if (strtolower($path_parts['extension']) == 'jpg' || strtolower($path_parts['extension']) == 'gif' || strtolower($path_parts['extension']) == 'png' || strtolower($path_parts['extension']) == 'jpeg') {
 
            echo "<div class=\"panel\">";
            echo "{$file['date']} <a href=\"" . $_path . $file['file'] . "\" rel=\"lytebox\" title=\"\">";
            echo "{$file['file']}: <img src=\"" . $_path . $file['file'] . "\" hspace=\"2\" border=\"0\">";
            echo "</a></div><br>";
 
        }
 
    }  
 
} 
?>

Open in new window

0
 
LVL 3

Expert Comment

by:albrieu
ID: 23622657
change line 67 to your path

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to implement server side field validation and display customized error messages to the client.
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question