This is a small and simple tutorial that will explain how to create a image gallery for your site.

The code is below and explanation then follows:

<html>
<head>
<title> An image gallery </title>
<style type="text/css">
body{
font-weight:bold;
margin-left:10%;
margin-right:10%;
margin-bottom:10%;
font-family:sans-serif;
border:10px solid black;
}
</style>
</head>
<body>

<?php
$i=0;
//replace with your own directory here
$dir="images/";
$dh=opendir($dir);
while($filename=readdir($dh))
{
$filepath_c=$dir.$filename;
if(is_file($filepath_c) and preg_match("#\.jpg$#",$filename))
{
$gallery[$i]=$filepath_c;
$i=$i+1;

}
}

sort($gallery);
foreach($gallery as $image)
{
$name=basename($image);
echo "<br/> <br/>" ;
echo "<hr />";
echo "<a href='$image'> image $name <br/>";
echo " <img src='$image' align='middle' alt='image $image' width=200 hieght=200 /> </a>";
echo "<br/>";
}

?>

</body>
</html>


Explanation:

The code is quite simple in the start a simple style tag, defines how the web page must be displayed and after that the main logic lies in the php code . We initialize a variable i for loop execution although it is not required but makes code more clearer.

We then define the directory under which files are stored replace the directory name /images.
with your own directory
Then we open a directory handle and read all the files under it by using readdir( ) function
we check whether its a file or not and use preg_match() for pattern matching

note: preg_match is a regular expression matcher in php, it requires a regular expression pattern and a string to match with.
In this case that string happens to be the entire filepath and the pattern is delimited by # and "#\.jpg$" signifies that only take files ending with .jpg extension you can remove this if you have no other file in your images directory

finally we sort the array obtained and then in foreach loop keep on adding image tags with the filename. Thats it a simple image gallery using php.

Do comment if post was helpfull.