简体   繁体   中英

Displaying images from folder in php

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.

Using glob and sort :

$files = glob("*.jpg");
sort($files);
foreach ($files as $file) {
    ....
}

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

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)); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM