How to create an image gallery in PHP from a folder

Question:

How to create an image gallery in PHP from a folder

Solution:

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

Simple Code:

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

$random_img = basename($images[array_rand($images)]);
foreach($images as $key=>$value)
{
  echo "<img src='$value' style='margin:10px'>";
}
?>

Returns:
The image file name in that images directory with image tags in a html page.


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>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>Image Gallery In PHP From a Folder</h2>

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

  foreach($images as $key=>$value)
  {
    echo "<img src='$value' style='margin:10px'>";
  }

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

Output:
How to create an image gallery in PHP from a folder


Image Folders In images directory is like,

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

Real Life Use of this Image Gallery:

If we want to make an image gallery for our blog posts / E-commerce products / User profile pictures and edit or delete them any time.
For that reason sometime we  need to create an image gallery and that is really helpful for admin to monetize that images.

Hope that helps you.

See Another tutorial how to create a random image gallery by php

Tags:
How to create an image gallery in PHP from a folder, 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 an image gallery in PHP from a folder How to create an image gallery in PHP from a folder Reviewed by Maniruzzaman Akash on October 17, 2017 Rating: 5

8 comments:

Powered by Blogger.