How to create a random image gallery from a directory in PHP

Question:

How to create a random image gallery from a directory in PHP?


Solution:

Suppose I have an image gallery in images/ folder. Then how to retrieve the images randomly to generate an image gallery.

Simple Code:

$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$random_img = basename($images[array_rand($images)]);

Returns:
The image file name in that images directory.


Code Explanation:
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

In this line,
look first glob function. Glob function in PHP is used to find pathnames matching a pattern. That means it looks for that path for given pattern. Here the files extenstion will be jpg, jpeg, png and gif.

And GLOB_BRACE = Expands {a,b,c} to match 'a', 'b', or 'c'

Full Code
<!DOCTYPE html>
<html>
<head>
 <title>Random Image Gallery In PHP From a Folder</title>
 <style type="text/css">
 img{
  width: 200px;
  margin: 10px;
  border: 1px solid #d4d5d7;
  padding: 10px;
  background: #d4d5d7;
 }
 h2{
  text-align: center;
  background: #d4d5d7;
  padding: 20px;
  border-bottom: 5px solid #35c8bd;
 }
</style>
</head>
<body>
 <div class="container">
  <h2>Random Image Gallery In PHP From a Folder</h2>

  <?php 
  
  for ($i = 1; $i < 10; $i++):
   $imagesDir = 'images/';
   $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
   $random_img = basename($images[array_rand($images)]);

   echo "<img src='images/$random_img'/>";

  endfor;

  ?>
 </div>
</body>
</html>

Output:
How to create a random image gallery from a directory in PHP


Image Folders In images directory is like,

How to create a random image gallery from a directory in PHP

Real Life Use of this Random Image Gallery:

When we make a user showing page or any blog posts home page and we need to show many posts or users.
But users may have not their profile pictures everyone, or some blog posts has not any image, then a random images gallery can be used to make the site more interactive.

In that case, first check if the user has an image or not. If he has no images then set the random image profile picture which is kept in a specific directory.



Hope that helps you.


Tags:
How to create a random image gallery from a directory in PHP, random gallery php, random image in php, php random images, php, Learn more about glob, glob example, php glob function example, glob real life example in php.make a random image from directories

How to create a random image gallery from a directory in PHP How to create a random image gallery from a directory in PHP Reviewed by Maniruzzaman Akash on October 15, 2017 Rating: 5

No comments:

Powered by Blogger.