Cai Griffith
Cai Griffith

Reputation: 1

PHP images from directory - Random order

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, '" />';
    }
}
}

Upvotes: 0

Views: 1759

Answers (4)

Alessandro
Alessandro

Reputation: 898

Please, follow this instruction: create a folder "php" into root of your website and put inside the following php file rotate.php... now create a folder "pic" and "xmas" into your root... you can chose the folder name or other things by editing the var $my_folder_holiday and $my_folder_default...

<?php
  ##########################################################
  # Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
  # Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
  ##########################################################
  function rotate($folder) {
    if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
      $list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
      $fileList = array();
      $img = '';
      foreach ($list as $file) {
        if ((file_exists($_SERVER['DOCUMENT_ROOT']  . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT']  . "/$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;
    } else {
      mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
    }
  }
  $my_gallery_month = date('m');
  $my_folder_default = 'pic';
  $my_folder_holiday = 'xmas';
  if ($my_gallery_month == 12) {
    $my_gallery = rotate($my_folder_holiday);
  } else {
    $my_gallery = rotate($my_folder_default);
  }
?>

The usage is very easy and works very well under PHP 7.4... if you have in the root of your website a folder "pic" and "xmas" 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 $my_gallery; ?>"><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>

This is another usage using FancyBox library:

<a href="/<?php include("php/rotate.php"); echo $my_gallery; ?>" data-fancybox><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>

Hope this helps...

Upvotes: 0

user2560539
user2560539

Reputation:

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

Upvotes: 1

cv-pls
cv-pls

Reputation: 421

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, '" />';
        }
    }
}

Upvotes: 8

rwhite
rwhite

Reputation: 430

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.

Upvotes: 3

Related Questions