Get random image from directory in PHP

  • Author: Sajjad Hossain
  • |
  • Added: Jan 11, 2016
  • |
  • In: All Questions

This article about gets a random image from a directory. If you want to use a random image for a link or an article then you can do that easily using PHP. There are nice and cool tricks to do this program. It's so easy for a developer to make this script and it's easy to use also. Let's see how we make this script for make a random image viewer in PHP. we will use PHP glob function fo that. this function will extract images from a folder.
first, we will create a function name as RandImg() then put this code into this function.

function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
return $randomImage;
}

we used $dir variable in RandImg() function to pass directory in this function so that we can use this function for a mutiple directory. We also used $dir . '*.{jpg,jpeg,png,gif} this script will detect only jpg,jpeg,png and gif images and GLOBE_BRACE for match jpg,jpeg,png,gif.
Let's see how this script will work, create an index.php file into your server then create a directory name as images and put some images into this directory. In index.php file write down this script and run this script on your server.

<?php
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
return $randomImage;
}
$link = "http://phpans.com";
$the_images = RandImg('images/');
$ImageWithLink = '<a href="'.$link.'"><img src="'.$the_images.'"></a>';
echo $ImageWithLink;
?>
This script is ready for use. this script will execute random image as result.

Top