开发者

PHP: read all files but randomly?

i wonder if there's a way of reading a directory in a random order.

With the following code i'm running through the directory thumbs and it's printing images on my website. However, they are always read alphabetically and i wonder if there's a way in doing this randomly?

<?php
$path = 'thumbs';
if开发者_JS百科 ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db') {
                print "<img class='thumb' src='$path/$file'/>";

        } else {
            //no proper file
        }
    }
    closedir($handle);
}
?>

thank you for your suggestions!

regards


why not put the results in an array and then randomly shuffling the array?


instead of printing the images put file names in an array, shuffle it when loop ends and make another loop after this for printing the values.


Try with this function:

function getDirContent($dir='./'){
if ( is_dir($dir) ) {
    $fd = @opendir($dir);
    while ( ($part = @readdir($fd)) == TRUE ) {
        clearstatcache();
        $dir_array[] = $part;
    }
    if($fd == TRUE) {
        closedir($fd);
    }
    if (is_array($dir_array)) {
        shuffle($dir_array);
        return $dir_array;
    } else {
        Return FALSE;
    }
}

}


$files = glob("$path/*.[JjGg][PpIi][GgFf]");
shuffle($files);


I know this is an old post but this code might be helpful for someone searching:

$dir = 'path/to/dir';
  if ( $handle = opendir($dir) ) {
  $files = array();
  while ( false !== ($file = readdir($handle)) ) {
  if ($file != '.' && $file != '..') {
     array_push($files,$file);
 }
}
  closedir($handle);
  shuffle($files); // <- THIS DID THE TRICK**
  foreach( $files as $file ) {
  echo $file;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜