0

Hello I have this code to show image from folder in php :

$handle = opendir(dirname(realpath(__FILE__)).'/galerija/accomodation/');
while($file = readdir($handle)) {
    if($file !== '.' && $file !== '..') {
        echo '<img src="galerija/accomodation/'.$file.'" rel="colorbox" />';
    }
}

and it's working everthing is fine but how can I set to show folder sorter by name or something, because I really need to sort that images and this script show's only random images.Thank you.

Niklas Modess
  • 2,521
  • 1
  • 20
  • 34

3 Answers3

1

Using glob and sort:

$files = glob("*.jpg");
sort($files);
foreach ($files as $file) {
    ....
}
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
0

You should first store the images ($files) to an array, for example $aImages[] = $file. The you can use several sort functions from PHP to sort your array. asort(), usort(), sort().... See http://php.net/manual/en/ref.array.php

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
0

You should find your answer here: Sorting files by creation/modification date in PHP

There are other similar posts where you could get another usefull function for sorting.

So that your code should look something like this:

if($h = opendir(dirname(realpath(__FILE__)).'/galerija/accomodation/')) {
  $files = array();
  while(($file = readdir($h) !== FALSE){
    if($file !== '.' && $file !== '..'){
       $files[] = stat($file);
    }
  }

  // do the sort
  usort($files, 'sortByName');

  // do something with the files
  foreach($files as $file) {
            echo '<img src="galerija/accomodation/'.$file.'" rel="colorbox" />';
  }
}

//some functions you can use to sort the files
//sort by change time
//you can change filectime with filemtime and have a similar effect
function sortByChangeTime($file1, $file2){
    return (filectime($file1) < filectime($file2)); 
}

function sortByName{
    return (strcmp($file1,$file2)); 
}
Community
  • 1
  • 1
Decebal
  • 1,376
  • 1
  • 21
  • 36
  • "syntax error, unexpected T_IF in "path to php" on line 5" how can i fix this –  Oct 09 '12 at 09:22
  • my last edit should do the trick, there was a semicolon that do not belong there, my fault – Decebal Oct 09 '12 at 11:58