For several hours I searched the Internet to implement the code I wanted. I have compiled several different answers that I found on the Internet. Here is the code:
<?php $folder = opendir("Images/Gallery Images/"); $i = 1; while (false != ($file = readdir($folder))) { if ($file != "." && $file != "..") { $images[$i] = $file; $i++; } } //This is the important part... for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit) $random_img = rand(1, count($images) - 1); if (!empty($images[$random_img])) { //without this I was sometimes getting empty values echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />'; echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug unset($images[$random_img]); //unset each image in array so we don't have double images } } ?>
Using this method, I was able to implement opendir without errors (since glob()
did not work for me), I was able to pull out 5 images for the carousel gallery and get rid of duplicate images and figure out empty values. One drawback of using my method is that the number of shots varies from 3 to 5 images in the gallery, probably due to the removal of empty values. Which did not bother me too much, as it works as needed. If someone can improve my method, I welcome you to do this. Working example (first carousel gallery on top of website): Eastfield Refinery
source share