PHP & MySQL, Demos, Tutorials

This tutorial will show you how to quickly create a gallery from a folder of images. Using PHP and making use of TimThumb a very handy image resizing script available from http://code.google.com/p/timthumb this script lets you resize an image very easily.

All images will be loaded in to a list, therefore apply some basic styling:

li{
    list-style-type:none;
    margin-right:10px;
    margin-bottom:10px;
    float:left;
}

Next define the image folder

 $dirname = "images/";

Then load all files into an array using a function called scandir to make sure you don't reference default files that exist within the array define an ignore list and pass any files you don't want loaded

$images = scandir($dirname);
$ignore = Array(".", "..");

Then loop through each item array and if its not contained in the ignore list echo the image to the screen using the TimThumb script (in this case I've called the file img.php) pass it the path to the images and also the width of the image the height will be adjusted automatically and set the zoom level 1 is no zoon while 0 is zoomed.

 foreach($images as $curimg){
            if(!in_array($curimg, $ignore)) {
                echo "<li><a href='".$dirname.$curimg."'><img src='img.php?src=".$dirname.$curimg."&w=300&zc=1' alt='' /></a></li>n ";
            }
}

That's it! I've wrapped all images around a link that points to the original image. this is a very basic example but from just a few lines of code I've got an automated image gallery!

The full script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Gallery from Folder Demo</title>
<style type="text/css">
<!--
li{
    list-style-type:none;
    margin-right:10px;
    margin-bottom:10px;
    float:left;
}

-->
</style></head>

<body>

<ul>
    <?php
        $dirname = "images/";
        $images = scandir($dirname);
        shuffle($images);
        $ignore = Array(".", "..");
        foreach($images as $curimg){
            if(!in_array($curimg, $ignore)) {
                echo "<li><a href='".$dirname.$curimg."'><img src='img.php?src=".$dirname.$curimg."&w=300&zc=1' alt='' /></a></li>n ";
            }
        }                 
    ?>
</ul>

</body>
</html>