PHP images from directory - Random order

2019-08-25 01:50发布

问题:

I have a page of my website which I use to store reference images..

Currently I just drop all of the images into a directory on my server and the php displays them how I like.

What i'd like to ask is how to I get them to display in a different random order every time the page is refreshed?

code is below:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');


if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);


foreach ($dir_contents as $file) {
    $file_type = strtolower(end(explode('.', $file)));

    if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
    echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
    }
}
}

回答1:

To guarantee that the order is different every time requires that you carry the data about the order in which they were displayed between page loads. However, this is not necessarily what you require - if you simply randomise the order every time then the higher the number of images in the directory the lower the chance you will get the same order twice.

You can simply use shuffle() to randomise the order of the array:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) == false) {
    echo 'Directory \'', $dir, '\' not found';
} else {
    $dir_contents = scandir($dir);
    shuffle($dir_contents);

    foreach ($dir_contents as $file) {
        $file_type = strtolower(end(explode('.', $file)));

        if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
            echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
        }
    }
}


回答2:

Look at shuffle function. http://php.net/manual/en/function.shuffle.php Since PHP is stateless, you'll either rescan your directory each time or assign the $dir_contents to a session variable. Then you could simple shuffle the session variable.

 if ($file !== '.' && $file !== '..' && in_array($file_type, suffle($file_display)) == true) {

Try that.



回答3:

Use php shuffle to the array of images created by scandir

 $dir = 'images';
 $file_display = array ('jpg', 'jpeg', 'png', 'gif');     
 if (file_exists($dir) == false) {
    echo 'Directory \'', $dir, '\' not found';
 } else {
    $dir_contents = scandir($dir);                    
    if(shuffle($dir_contents)) {                    
      foreach ($dir_contents as $file) {
         $info = new SplFileInfo($file);

      // scandir returns an array of files and,or directories 
      // so we should check if $file is a file 
      // and that it's extension matches the allowed ones 
      // which are ('jpg', 'jpeg', 'png', 'gif')

         if(is_file($file) && in_array($info->getExtension(),$file_display)) {
            echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';                                  
          }          
      }        
    } else {
    echo 'Error applying random order!';
 }
}


回答4:

Please, follow this instruction: create a folder "php" into root of your website and put inside the following php file rotate.php...

<?php
  ###############################################
  # Simple Php Image Rotator - 1.1 - 24.10.2018 #
  # Alessandro Marinuzzi - http://www.alecos.it #
  ###############################################
  function rotate($folder) {
    $list = scandir($folder);
    $fileList = array();
    $img = '';
    foreach ($list as $file) {
      if (is_file($folder . '/' . $file)) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
          $fileList[] = $file;
        }
      }
    }
    if (count($fileList) > 0) {
      $imageNumber = time() % count($fileList);
      $img = $folder . '/' . $fileList[$imageNumber];
    }
    return $img;
  }
?>

The usage is very easy and works very well under PHP 7.2... if you have in the root of your website a folder "pic" containing your images, please, put into your index.php (or other file php located in the root):

<a href="/<?php include("php/rotate.php"); echo rotate("pic"); ?>">

This is another usage using highslide library:

<a href="/<?php include("php/rotate.php"); echo rotate("pic"); ?>" class="highslide" onclick="return hs.expand(this)"><img src="/<?php echo rotate("pic"); ?>" title="Click To Enlarge" alt="Random Gallery" width="90" height="67"></a>

Hope this helps...