matt
matt

Reputation: 44353

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 ($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

Upvotes: 0

Views: 923

Answers (5)

Pexsol
Pexsol

Reputation: 561

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

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157900

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

Upvotes: 0

Aleksandar Vucetic
Aleksandar Vucetic

Reputation: 14953

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

}

Upvotes: 0

tazphoenix
tazphoenix

Reputation: 194

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.

Upvotes: 0

corroded
corroded

Reputation: 21584

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

Upvotes: 3

Related Questions