I have one directory called images/tips.
Now in that directory I have many images which can change.
I want the PHP script to read the directory, to find the images, and out of those images found to pick a random image.
Any idea on how to do this?
$imagesDir = 'images/tips/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)]; // See comments
You can send a 2nd argument to array_rand() to get more than 1.
$images = glob('images/tips/*');
return $images[rand(0, count($images) - 1)];
However, this doesn't ensure that the same image isn't picked twice consecutively.
<?php
foreach (glob("gallery/*") as $filename) {
echo '<li><img src="'.$filename.'" alt="" /> </li>';
}
?>
Look at this code, use it definitely if useful for you. It loads all files from folder and prints them in above format. I made this code to use with lightbox.
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach($list as $file)
{
if(!isset($img))
{
$img = '';
}
if(is_file($dir . '/' . $file))
{
$ext = end(explode('.', $file));
if($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG')
{
array_push($arr, $file);
$img = $file;
}
}
}
if($img != '')
{
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
Agreed with alexa.
Use simple function.
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
return $randomImage;
}
$the_image = RandImg('images/tips/');
echo $the_image;
$folder = "images";
$results_img_arr = array();
if (is_dir($folder))
{
if ($handle = opendir($folder))
{
while(($file = readdir($handle)) !== FALSE)
{
if(!in_array($file,array(".","..")))
$results_img_arr[] = $folder."/".$file;
}
closedir($handle);
}
}
$ran_img_key = array_rand($results_img_arr);
$img_path = $results_img_arr[$ran_img_key];
You can use opendir() to read in the filenames from that directory, storing each filename in an array. Then use rand() with a min and max corresponding to your array keys to select an item from the array.
Simpler:
$directory = "medias/photos/";
$img = glob($directory . "*.jpg");
shuffle($img);
I wrote a simple php script for my personal use. Now I want share it with stackoverflow's community. Usage is simple: create a folder "php" into root of your Web Server and put inside this file php rotate.php... now create two folders into your root called "pic" and "xmas"... you can adjust the folder names 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);
}
?>
This script was tested under PHP 7.0/7.1/7.2/7.3 and PHP 7.4 and works fine. Usage (for example in root you may have a folder "pic" and "xmas" containing your images):
<img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67">
Other usage using FancyBox library:
Hope this Helps.
Load folder with images:
$folder = opendir(images/tips/);
Build table out of files/images from directory:
$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
$images[$i]= $file;
$i++;
}
}
Pick random:
$random_img=rand(0,count($images)-1);
Show on page:
echo '<img src="images/tips'.$images[$random_img].'" alt="" />';
Hope it helps. Of course enclose it in <?php ?>.
Related
Im trying to select random image from random directory. I make function to get random directory and another function to get random image from that directory. Okay, but its not working, its getting random directory and random image from another directory
<?php
function showRandomDir()
{
$files = glob('images/portfolio/*/', GLOB_ONLYDIR);
shuffle($files);
$files = array_slice($files, 0, 1);
foreach($files as $file)
{
return $file;
}
}
function rotate2()
{
$list = scandir(showRandomDir());
$fileRotateList = array();
$img = '';
foreach($list as $fileRotate)
{
if (is_file(showRandomDir() . htmlspecialchars($fileRotate)))
{
$ext = strtolower(pathinfo($fileRotate, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png')
{
$fileRotateList[] = $fileRotate;
}
}
}
if (count($fileRotateList) > 0)
{
$imageNumber = time() % count($fileRotateList);
$img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);
}
return $img;
}
At the beginning of your rotate2() function, you call showRandomDir() to get the contents of a random directory:
$list = scandir(showRandomDir());
But then at the end, you call showRandomDir() again, so you get a different random directory.
(Well, a new one, that's probably different, but could randomly be the same.)
$img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);
You need to save the first call into a variable instead, and reuse that variable instead of calling showRandomDir() a second time.
$dir = showRandomDir();
$list = scandir($dir);
// ... the rest of the code in between
$img = $dir . urlencode($fileRotateList[$imageNumber]);
I'm working on an image compression cron job for my sites assets. The problem I'm facing is that the code works fine locally but not on on the remote server.
I'm using scandir, I've seen the related post: php scandir() not showing files - only showing directories users were saying that it isn't recursive. However on my local system I've replicated the folder structure on the remote server and it works perfectly.
I have the following function which I use for both folders and files.
function getFilesInDir($path)
{
$directory = $path;
if (is_dir($directory))
{
$files = array();
foreach(scandir($directory) as $file)
{
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
// }
}
}
return $files;
}
When I use var_dump on the the folder I get the right results. It lists all folders within the specified directory.
Usage
$folders = getFilesInDir("site/assets/files");
foreach($folders as $folder)
{
$files = getFilesInDir($folder);
//...Do the rest
So var_dump($folders) displays the correct directories. When I do var_dump($files) I get NULL NULL NULL NULL NULL.
I reiterate, this works fine on my local machine but not my remote server.
Complete Code (if it's of use)
It's not pretty I know but it works and I'm on a deadline.
<?php
// $folders = getFilesInDir(getcwd());
$folders = getFilesInDir("site/assets/files");
foreach($folders as $folder)
{
$files = getFilesInDir($folder);
var_dump($files);
if ($files)
{
$x = array_filter($files, "isImage");
foreach($files as $f)
{
$path_parts = pathinfo($f);
if (#$path_parts['extension'] != null)
{
if (filesize($folder . "/" . $f) > 1000000)
{
echo $f . " - " . filesize($folder . "/" . $f) . "<br />";
if ($path_parts['extension'] == "jpg" || $path_parts['extension'] ==
"jpeg" || $path_parts['extension'] == "png")
{
// Make bin folder if not exists
MakeFolder($folder . "/");
// Compress file in folder to bin folder
$d = compress($folder . "/" . $f, $folder . "/bin/" . $f, 30);
// Delete files in base
unlink($folder . "/" . $f);
// Move files from bin to root
rename($folder . "/bin/" . $f, $folder . "/" . $f);
}
}
}
}
}
}
function MakeFolder($path)
{
if (!file_exists($path . "/bin/"))
{
mkdir($path . "/bin/", 0777, true);
}
}
function isImage($var)
{
$path_parts = pathinfo($var);
if (#$path_parts['extension'])
{
if ($path_parts['extension'] == "jpg" || $path_parts['extension'] == "jpeg" || $path_parts
['extension'] == "png")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
function getFilesInDir($path)
{
$directory = $path;
if (is_dir($directory))
{
$files = array();
foreach(scandir($directory) as $file)
{
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
// }
}
}
return $files;
}
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
?>
scandir only returns the filenames without path. You need to append the path of the original folder to the new one's.
$path = "site/assets/files"
$folders = getFilesInDir($path);
foreach($folders as $folder)
{
$files = getFilesInDir($path . "/" . $folder);
var_dump($files);
Hope this does it.
I am using WordPress. I have an image folder like mytheme/images/myimages.
I want to retrieve all the images name from the folder myimages
Please advice me, how can I get images name.
try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo $image;
}
you can do it simply with PHP opendir function.
example:
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="pictures/'.$file.'" border="0" />';
}
}
When you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
If you do not want to check image type then you can use this code also
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
}
for more information
PHP Manual
Here is my some code
$dir = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);
function Get_ImagesToFolder($dir){
$ImagesArray = [];
$file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];
if (file_exists($dir) == false) {
return ["Directory \'', $dir, '\' not found!"];
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_type, $file_display) == true) {
$ImagesArray[] = $file;
}
}
return $ImagesArray;
}
}
This answer is specific for WordPress:
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';
$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();
foreach ( $image_paths as $image ) {
$image_names[] = str_replace( $media_dir, '', $image );
$image_urls[] = str_replace( $media_dir, $media_url, $image );
}
// --- You now have:
// $image_paths ... list of absolute file paths
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
// $image_urls ... list of absolute file URLs
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg
// $image_names ... list of filenames only
// e.g. sample.jpg
Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:
From Uploads directory:
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );
From Parent-Theme
// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );
From Child-Theme
// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$dir = "mytheme/images/myimages";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);
Very fast because you only scan the needed directory.
//path to the directory to search/scan
$directory = "";
//echo "$directory"
//get all files in a directory. If any specific extension needed just have to put the .extension
//$local = glob($directory . "*");
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
//print each file name
echo "<ul>";
foreach($local as $item)
{
echo '<li>'.$item.'</li>';
}
echo "</ul>";
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
<?php
$galleryDir = 'gallery/';
foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
{echo "\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "";}?>
UIkit php folder gallery
https://webshelf.eu/en/php-folder-gallery/
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
echo '<img src="'.$image.'" /><br />';
}
get all the images from a folder in php without database
$url='https://demo.com/Images/sliderimages/';
$dir = "Images/sliderimages/";
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
$data=array();
if (file_exists($dir) == false) {
$rss[]=array('imagePathName' =>"Directory '$dir' not found!");
$msg=array('error'=>1,'images'=>$rss);
echo json_encode($msg);
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
#$file_type = strtolower(end(explode('.', $file)));
// $file_type1 = pathinfo($file);
// $file_type= $file_type1['extension'];
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
$data[]=array('imageName'=>$url.$file);
}
}
if(!empty($data)){
$msg=array('error'=>0,'images'=>$data);
echo json_encode($msg);
}else{
$rees[]=array('imagePathName' => 'No Image Found!');
$msg=array('error'=>2,'images'=>$rees);
echo json_encode($msg);
}
}
You can simply show your actual image directory(less secure). By just 2 line of code.
$dir = base_url()."photos/";
echo"Photo Directory";
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, '" />';
}
}
}
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, '" />';
}
}
}
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.
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!';
}
}
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):
<img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67">
This is another usage using FancyBox library:
Hope this helps...
I am wondering about a "better" way of pulling a random image from a folder.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
here is how I do it today
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
Try this:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
Below code validate image list by image extension.
<?php
function validImages($image)
{
$extensions = array('jpg','jpeg','png','gif');
if(in_array(array_pop(explode(".", $image)), $extensions))
{
return $image;
}
}
$images_folder_path = ROOT.'/web/files/Header/';
$relative_path = SITE_URL.'/web/files/Header/';
$images = array_filter(array_map("validImages", scandir($images_folder_path)));
$rand_keys = array_rand($images,1);
?>
<?php if(isset($images[$rand_keys])): ?>
<img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" />
<?php endif; ?>
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach ($list as $file) {
if (!isset($img)) {
$img = '';
}
if (is_file($dir . '/' . $file)) {
$ext = end(explode('.', $file));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG') {
array_push($arr, $file);
$img = $file;
}
}
}
if ($img != '') {
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
I searched the internet for hours on end to implement the code to what I wanted. I put together bits of various answers I found online. 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 with no errors (as glob() wasn't working for me), I was able to pull 5 images for a carousel gallery, and get rid of duplicate images and sort out the empty values. One downside to using my method, is that the image count varies between 3 and 5 images in the gallery, probably due to the empty values being removed. Which didn't bother me too much as it works as needed. If someone can make my method better, I welcome you to do so.
Working example (the first carousel gallery at top of website): Eastfield Joinery