How To Make Your Own Image Gallery With An Administration

on Sat Jul 05 08:36:24 GMT 2008 in PHP and viewed 35016 times

One thing everyone searches for is a great image gallery. Whether it’s to show off your work as a web designer or some pictures of your kid’s birthday, an easy way to upload and identify your images is always great. This tutorial will teach you how to create an image gallery: the administration comes complete with a login check, an upload form, a system for describing your images in a database, and the front end has everything including showing thumbnails of all your images, how to use the very great Script.aculo.us library for some great effects, and a javascript slideshow.


Starting Off Quick

Well, the introduction’s up there, so let’s start this off running. First thing to do is to create the MySQL table.


CREATE TABLE `gallery` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `description` text,
  `image` text,
  `basename` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`id`)
);

That’s a pretty easy table. Each image will be identified with its own id, title, description, image (which will be the full location of the image) and basename (which will be used for deleting individual images).

The Administration Panel

The administration panel. The area that lets you add and delete images. Well, this will be an adventure.

First things first, you need to be able to protect this area. But first, the basics for the page.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Image Gallery Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
* { 
    font-size: 14px;
    line-height: 150%; 
    font-family: Trebuchet MS, Verdana, Arial, sans-serif;
    }
h1 {
    background-color: #cccccc;
    padding: .3em;
    }
h1 a { color: #000;
    font-size: 1.3em;
    }
img { height: 100px;
    width: 100px;
    }
</style>
</head>
<body>
<h1><a href="admin.php">Image Gallery Administration</a></h1>

<?php

// PHP Code will go here

?>
</body>
</html>

It’s a very easy page. The CSS is easy as well, it basically sets up the font size and types, as well as some basic styling for the header tags. Also is the styling for the image element. Each element that will be previewed on the adminisration page will only be 100×100 pixels. If each image were to be displayed at their full size, you can imagine how it would look and how slow it would load. But otherwise, just a normal page. Now you get into the authorising.

Login System

This is actually going to be exactly the same as in the Statistics Suite.


<?php
if($_GET["action"] == "2"){
    $username = $_POST["username"];
    $password = $_POST["password"];
    if($username == "username" && $password == "password"){
        setcookie("statisticslogged", "yourpassphrase", 0);
        header("Location: statistics.php");
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Image Gallery Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
* { 
    font-size: 14px;
    line-height: 150%; 
    font-family: Trebuchet MS, Verdana, Arial, sans-serif;
    }
h1 {
    background-color: #cccccc;
    padding: .3em;
    }
h1 a { color: #000;
    font-size: 1.3em;
    }
img { height: 100px;
    width: 100px;
    }
</style>
</head>
<body>
<h1><a href="admin.php">Image Gallery Administration</a></h1>

<?php
if($_COOKIE["statisticslogged"] == "yourpassphrase"){

//Whole Adminisration goes here

}
else {
?> 
    <h2>Log in</h2> 
    <form action="statistics.php?action=2" method="post"> 
      <label for="username"><b>Username:</b></label> 
      <input type="text" name="username" /> 
      <br /> 
      <label for="password"><b>Password:</b></label> 
      <input type="password" name="password" /> 
      <br /> 
      <input type="submit" value="Login!" /> 
    </form> 
<?
}

?>
</body>
</html>

There’s your page now. An easy login form that checks for your cookie to be set to a certain passphrase and if not, to be shown a login form.

And before you get to the meat of the administration, why don’t you set up the other basic part of the administration: namely, the database connection and the switch statement.


$connection = mysql_connect("database",
                            "username",
                            "password");
    mysql_select_db("database", $connection);

switch($_GET["action"]){

// cases will go here

}

That’s pretty easy. A MySQL connection and then a switch statement, hinging on the GET variable “action”.

Next: Listing Images

Well, now that you’re into your image gallery area, you should now start to list all the images. Or at least, get the code there so that when you do add images, you will be able to see them later.


    default:
    $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
    echo "<table>";
    while($r = mysql_fetch_array($select)){
        extract($r);
        ?>
        <tr>
            <td><b><?=$title?></b></td>
            <td><?=$description?></td>
            <td><img alt="<?=$title?>" src="<?=$image?>" /></td>
            <td><a href="admin.php?action=edit&amp;id=<?=$id?>">Edit Picture</a></td>
            <td><a href="admin.php?action=delete&amp;id=<?=$id?>">Delete Picture</a></td>
        </tr>
        <?
    }
    echo "</table>";
    break;//end default

This is relatively easy. Just select each image from the gallery, newest first. Then start a table. Then loop through each row in the table outputting in a row and table cell the title, the description, a preview (remember the CSS?), and two links to edit or delete the picture. The variable $image will be defined when you add an image as the absolute path to finding the image.

Speaking of adding an image, the form too will be on the same page. Add this code beneath the echo "</table>";


    ?>
<form enctype="multipart/form-data" method="post" action="admin.php?action=add">
<label for="title"><b>Title: </b></label><br />
<input type="text" name="title" /><br />
<label for="description"><b>Description: </b></label><br />
<textarea name="description" rows="5" cols="35"></textarea><br />
<input type="file" name="image" /><br />
<input type="submit" value="Add Image" />
</form>
    <?

This is a standard upload form. Basically normal, the form method is post, the action will be add, and there’s the title and description fields. But in the <form> element, there’s the “enctype” attribute, which has to be set to “multipart/form-data,” signaling a file upload. Also very imperative to the file upload is the line:


<input type="file" name="image" />

This is an input type of file, and has the name image. Pretty simple. It creates the cool little Browse button and the file upload area.

Now you have everything you need to add an image. All you need now is to… add an image.

Adding an Image Backend


if(isset($_FILES["image"])){
            $file = $_FILES['image'];
            $title = htmlspecialchars($_POST["title"]);
            $description = htmlspecialchars($_POST["description"]);
            $basename = date("d-m-Y-G-j-s-").basename($file['name']);
            if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){
                if(move_uploaded_file($file['tmp_name'], $basename) && 
mysql_query("INSERT INTO gallery VALUES('', '$title', '$description', 
'http://www.shadow-fox.net/examples/imagegallery/$basename', '$basename')") or die(mysql_error())){
                    echo "Moved File<br />";
                    echo "Data Added.";
                }
                else {
                    "Couldn't move";
                }
            }//is an image
            else {
                echo "This isn't an image<br />";
                echo $file['type'];
            }//isn't image

        }//end isset file
        else {
        echo "File isn't set";
        }

Very hefty chunk of code. But we can take this apart piece by piece.


if(isset($_FILES["image"])){

Checks if there is an image. Otherwise, you don’t even need to do anything. The point is to add an image.


$file = $_FILES['image'];
$title = htmlspecialchars($_POST["title"]);
$description = htmlspecialchars($_POST["description"]);
$basename = date("d-m-Y-G-j-s-").basename($file['name']);

First $file is set to the image to make things a bit easier. Then title and description are cleard up. The final thing is to isolate the basename of the image. $basename is set to the date and time first (to make sure images won’t have the same name) and is concatenated onto the basename of the file. The function basename() takes the file’s name and finds just image.jpg instead of /place/tmp/image.jpg.


if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){

This big if statement basically checks the type of the file against all the image types to see if the file is an image. You don’t want an .mp3 uploaded or something.


if(move_uploaded_file($file['tmp_name'], $basename) && 
mysql_query("INSERT INTO gallery VALUES('', '$title', '$description', 
'http://www.shadow-fox.net/examples/imagegallery/$basename', '$basename')") or die(mysql_error())){
                    echo "Moved File<br />";
                    echo "Data Added.";
                }
                else {
                    "Couldn't move";
                }
            }//is an image
            else {
                echo "This isn't an image<br />";
                echo $file['type'];
            }//isn't image

This is basically one big check. The function move_uploaded_file does just what it says: it moves a file to a place on the server. It uses the temporary name of the file through $file[‘tmp_name’] and uploads it to a location. Of course, for this purpose it is moved to the same area as the admin.php file, but you might want to move it to somewhere like /uploads. In that case put move_uploaded_file($file[‘tmp_name’], ”/uploads/”.$basename). The second function is the basic insert statement. First is the id, then the title, description, full image path, and the basename. You will probably want to change the url in the image field to your own location. The basename is for deleting the file. You can’t delete something through the absolute path. The rest of the code is just to say “Hey the file was uploaded!” or “Hey, this isn’t an image and this is the type of file you uploaded!”

And now you should be able add an image. So go to it, add a few. See what happens. Now, if you need to edit an image (whether it’s changing the description or adding a new image) go on to editing an image.

Edit An Image


case "edit":
        $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $id = $row[0];
        $title = $row[1];
        $description = $row[2];
        $image = $row[3];
        $basename = $row[4];
        ?>
        <img src="<?=$image?>" alt="<?=$title?>" /><br /><br />
        <form action="admin.php?action=postedit&amp;id=<?=$id?>" method="post" enctype="multipart/form-data">
            <label for="title"><b>Title: </b></label><br />
            <input type="text" name="title" value="<?=$title?>" /><br />
            <label for="description"><b>Description: </b></label><br />
            <textarea name="description" rows="5" cols="35"><?=$description?></textarea><br />
            Leave Alone If You Want The Same Image: <br />
            <input type="file" name="image" /><br />
            <input type="submit" value="Edit Image" />
        </form>
        <? 
break;

It’s not that bad. It first fetches the row from the value in $_GET[“id”] and gets it all out into easy variables. Then the image is displayed so you know where you are. Then comes the form. There’s all the basic info, just like the adding form, except for the text that tells you that, unless you want your other image to be deleted, to leave the upload form alone and of course the values so you know the previous values. Pretty basic.

Actually Editing the Image Row and Image


case "postedit":
        foreach($_POST as $key => $value){
            $$key = htmlspecialchars($value);
        }
        $id = $_GET["id"];
        $select = mysql_query("SELECT basename FROM gallery WHERE id = ".$id) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $basename0 = $row[0];
        if(mysql_query("UPDATE gallery SET title = '".$title."', description = '".$description."'") or die(mysql_error())){
            echo "Updated.<br />";
            if($_FILES["image"]){
                $file = $_FILES["image"];
                $basename = date("d-m-Y-G-j-s-").basename($file['name']);
                if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){
                    if(unlink($basename0) && move_uploaded_file($file['tmp_name'], $basename)){
                        echo "Moved File<br />";
                        echo "<img src='$basename' /><br />";
                        if(mysql_query("UPDATE gallery SET basename = '".$basename."', 
image = 'http://www.shadow-fox.net/examples/imagegallery/$basename'") 
or die(mysql_error())){
                            echo "Image Location updated.";
                        }
                        else {
                            echo "Image Location could not be updated.";
                        }
                    }
                    else {
                        "Couldn't move";
                    }
                }//is an image
            }//if file is there
        }//updated
        else {
            echo "Could not update.";
        }//didn't update
    break;

Again, let’s take this piece by piece.


foreach($_POST as $key => $value){
            $$key = htmlspecialchars($value);
        }
        $id = $_GET["id"];
        $select = mysql_query("SELECT basename FROM gallery WHERE id = ".$id) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $basename0 = $row[0];

This is the basic variable setting code. You need to separate all the POST variables out for more ease, and then to GET the id, find the row, and the initial basename as $basename0.


if(mysql_query("UPDATE gallery SET title = '".$title."', description = '".$description."'") or die(mysql_error())){
            echo "Updated.<br />";

This is just the start. At first you just need to be able to update the row. If that happens, you get the updated print to the screen.


if($_FILES["image"]){
                $file = $_FILES["image"];
                $basename = date("d-m-Y-G-j-s-").basename($file['name']);
                if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || 
$file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){

This is just like adding the file. Check if there is a file, get the new basename, and check if the file type is an image. (Either a .gif, .jpg, .jpeg, or .png)


if(unlink($basename0) && move_uploaded_file($file['tmp_name'], $basename)){
                        echo "Moved File<br />";
                        echo "<img src='$basename' /><br />";

The function unlink() basically deletes a file. Obviously for this purpose the file will be in the same directory as admin.php, but if you have the image in ”/uploads” or something, change the argument accordingly.

The second function is one you know. The script then moves the file to its new home and gives you a message and shows it to prove it is indeed there.


if(mysql_query("UPDATE gallery SET basename = '".$basename."', 
image = 'http://www.shadow-fox.net/examples/imagegallery/$basename'") 
or die(mysql_error())){
                            echo "Image Location updated.";
                        }
                        else {
                            echo "Image Location could not be updated.";
                        }
                    }
                    else {
                        "Couldn't move";
                    }
                }//is an image
            }//if file is there
        }//updated
else {
            echo "Could not update.";
        }//didn't update

The only important thing here is the query to update the row, telling the row of the new basename and absolute path. This comes after the original update just because it should only update if there is an image uploaded for one, and also because you need to make sure the image was uploaded. The rest of the code is just left over closing braces and echoes.

Now you can edit an image! Try it out, both without uploading a new image, and with uploading a new image.

Deleting an Image


        $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $unlink = unlink($row[4]);
        if($unlink && mysql_query("DELETE FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error())){
            echo "Image Deleted.";
        }
        else {
            echo "Image Could Not Be Deleted.";
        }

This is small enough to not need a piece by piece explanation I believe. The first thing to do is to find the row and to fetch the basename of the file. Then the file is deleted and so is the row. It’s as easy as that. Again, change the unlink function if your image is uploaded in a different area.

Admin Panel Conclusion

There is your administration in full. You should now be able to add/edit/delete an image. Enjoy it, try it out.


<?php
if($_GET["action"] == "2"){
    $username = $_POST["username"];
    $password = $_POST["password"];
    $referrer = "http://shadow-fox.net/examples/statistics/";
    if($username == "username" && $password == "password"){
        setcookie("statisticslogged", "yourpassphrase", 0);
        header("Location: statistics.php");
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Image Gallery Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
* { 
    font-size: 14px;
    line-height: 150%; 
    font-family: Trebuchet MS, Verdana, Arial, sans-serif;
    }
h1 {
    background-color: #cccccc;
    padding: .3em;
    }
h1 a { color: #000;
    font-size: 1.3em;
    }
img { height: 100px;
    width: 100px;
    }
</style>
</head>
<body>
<h1><a href="admin.php">Image Gallery Administration</a></h1>

<?php
if($_COOKIE["statisticslogged"] == "yourpassphrase"){
    $connection = mysql_connect("localhost",
                            "username",
                            "password");
    mysql_select_db("database", $connection);

switch($_GET["action"]){

    default:
    $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
    echo "<table>";
    while($r = mysql_fetch_array($select)){
        extract($r);
        ?>
        <tr>
            <td><b><?=$title?></b></td>
            <td><?=$description?></td>
            <td><img alt="<?=$title?>" src="<?=$image?>" /></td>
            <td><a href="admin.php?action=edit&amp;id=<?=$id?>">Edit Picture</a></td>
            <td><a href="admin.php?action=delete&amp;id=<?=$id?>">Delete Picture</a></td>
        </tr>
        <?
    }
    echo "</table>";
    ?>
<form enctype="multipart/form-data" method="post" action="admin.php?action=add">
<label for="title"><b>Title: </b></label><br />
<input type="text" name="title" /><br />
<label for="description"><b>Description: </b></label><br />
<textarea name="description" rows="5" cols="35"></textarea><br />
<input type="file" name="image" /><br />
<input type="submit" value="Add Image" />
</form>
    <?
    break;//end default

    case "add":
        if(isset($_FILES["image"])){
            $file = $_FILES['image'];
            $title = htmlspecialchars($_POST["title"]);
            $description = htmlspecialchars($_POST["description"]);
            $basename = date("d-m-Y-G-j-s-").basename($file['name']);
            if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){
                if(move_uploaded_file($file['tmp_name'], $basename) && 
mysql_query("INSERT INTO gallery VALUES('', '$title', '$description', 
'http://www.shadow-fox.net/examples/imagegallery/$basename', '$basename')") 
or die(mysql_error())){
                    echo "Moved File<br />";
                    echo "Data Added.";
                }
                else {
                    "Couldn't move";
                }
            }//is an image
            else {
                echo "This isn't an image<br />";
                echo $file['type'];
            }//isn't image

        }//end isset file
        else {
        echo "File isn't set";
        }

    break;//end add

    case "edit":
        $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $id = $row[0];
        $title = $row[1];
        $description = $row[2];
        $image = $row[3];
        $basename = $row[4];
        ?>
        <img src="<?=$image?>" alt="<?=$title?>" /><br /><br />
        <form action="admin.php?action=postedit&amp;id=<?=$id?>" method="post" enctype="multipart/form-data">
            <label for="title"><b>Title: </b></label><br />
            <input type="text" name="title" value="<?=$title?>" /><br />
            <label for="description"><b>Description: </b></label><br />
            <textarea name="description" rows="5" cols="35"><?=$description?></textarea><br />
            Leave Alone If You Want The Same Image: <br />
            <input type="file" name="image" /><br />
            <input type="submit" value="Edit Image" />
        </form>
        <? 
    break;

    case "postedit":
        foreach($_POST as $key => $value){
            $$key = htmlspecialchars($value);
        }
        $id = $_GET["id"];
        $select = mysql_query("SELECT basename FROM gallery WHERE id = ".$id) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $basename0 = $row[0];
        if(mysql_query("UPDATE gallery SET title = '".$title."', description = '".$description."'") or die(mysql_error())){
            echo "Updated.<br />";
            if($_FILES["image"]){
                $file = $_FILES["image"];
                $basename = date("d-m-Y-G-j-s-").basename($file['name']);
                if($file['type'] == 'image/gif' || $file['type'] == "image/jpeg" || $file['type'] == "image/pjpeg" || $file['type'] == 'image/png'){
                    if(unlink($basename0) && move_uploaded_file($file['tmp_name'], $basename)){
                        echo "Moved File<br />";
                        echo "<img src='$basename' /><br />";
                        if(mysql_query("UPDATE gallery SET basename = '".$basename."', 
image = 'http://www.shadow-fox.net/examples/imagegallery/$basename'") or die(mysql_error())){
                            echo "Image Location updated.";
                        }
                        else {
                            echo "Image Location could not be updated.";
                        }
                    }
                    else {
                        "Couldn't move";
                    }
                }//is an image
            }//if file is there
        }//updated
        else {
            echo "Could not update.";
        }//didn't update
    break;

    case "delete":
        $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
        $row = mysql_fetch_row($select);
        $unlink = unlink($row[4]);
        if($unlink && 
mysql_query("DELETE FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error())){
            echo "Image Deleted.";
        }
        else {
            echo "Image Could Not Be Deleted.";
        }
    break;

}//end switch
}
else {
?> 
    <h2>Log in</h2> 
    <form action="statistics.php?action=2" method="post"> 
      <label for="username"><b>Username:</b></label> 
      <input type="text" name="username" /> 
      <br /> 
      <label for="password"><b>Password:</b></label> 
      <input type="password" name="password" /> 
      <br /> 
      <input type="submit" value="Login!" /> 
    </form> 
    <?
}
    ?>
</body>
</html>

Image Gallery Time

Well, now that you hopefully have a few images, its time to let everyone see them with your image gallery. This page takes advantage of the Script.aculo.us library, so you may want to download that before you move on.

Well, now let’s set up the page.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Image Gallery</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="javascripts/prototype.js" type="text/javascript"></script>
<script src="javascripts/scriptaculous.js" type="text/javascript"></script>
<script type="text/javascript">
/*javascripts*/
</script>
<style type="text/css">
* { 
    font-size: 14px;
    line-height: 150%; 
}
body { 
    font-family: Trebuchet MS, Verdana, Arial, sans-serif;
    background: url(gradient.jpg);
    background-repeat: repeat-x; 
}
h1 { 
    margin-left: 10em; 
}
h1 a {
    font-size: 1.75em;
}

#slideshow {
    margin-left: 5em;
    font-size: 1.5em;
}

/* Images */

#images {
    padding: 2em;
}

#images img {
    width: 150px;
    height: 150px;
    margin-right: 1em;
}

#bigpicture { 
    background-color:#CFDCE6;
    padding:2em;
    border:2px solid black;
}    
</style>
</head>
<body>
<h1><a href="gallery.php">Image Gallery</a></h1>
<h2>What We're About</h2>
<p>
    This was an image gallery that was conceived of, designed, and coded very quickly for a tutorial for the 
    <a href="http://www.shadow-fox.net">Shadow Fox Network</a> by <a href="http://blog.shadow-fox.net">Ben Hirsch.</a>
</p>

<a href="gallery.php?action=slideshow" id="slideshow">Full Slideshow</a><br /><br />

<!--PHP Code-->

</body>
</html>

Well, that’s the basic page. The first is to include the javascript libraries for the cool effects. Then there’s the CSS. All of it is basic styling. #images will be a div where each image inside will be a thumbnail of the full image.

Listing the Images


<?php
    $connection = mysql_connect("localhost",
                            "username",
                            "password");
    mysql_select_db("database", $connection);

    switch($_GET["action"]){

        default:
        echo '<div id="images">';
        $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
        while($r = mysql_fetch_array($select)){
            extract($r);
            echo "<a href='gallery.php?action=fullimage&amp;id=$id'><img src='$image' alt='$title' /></a>";
        }
        echo '</div>';
        break;//end default
}
?>

First is connecting to the database. Pretty obvious. Then there’s the default case.

First is the beginning of the <div> element. Then just select all of the images and echo each out as an image with in a link which will go to the action “fullimage” to display the image and it’s title/description.

Now of course the whole point of this tutorial is to get some cool javascripty effects in there. So let’s start with the thumbnail of the image. Instead, you should be able to click on the image and view the full image in a cool little animation. So let’s start that.


echo "<a href='gallery.php?action=fullimage&amp;id=$id' 
onclick=\"bigImage('".htmlspecialchars($image)."', '".htmlspecialchars($title)."', 
'".htmlspecialchars($description)."'); return false;\"><img src='$image' alt='$title' /></a>";

That’s a mouthfull. The interesting part is the onclick attribute. The javascript function is called bigImage(). The arguments are the image, the title, and the description. The main part is the “return: false;” That’s what tells the page not to follow the link. Now you need to actually create the function.


function bigImage(picture, title, description){
    var image = $("images");
    var images = image.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++){
        Effect.Fade(images[i])
    }

    var div = document.createElement("div");
    div.innerHTML = "<b>"+title+"</b>";
    div.innerHTML = div.innerHTML + "<p>"+description+"</p>";
    div.innerHTML = div.innerHTML + "<img src='"+picture+"' alt='"+title+"' /><br />";
    div.innerHTML = div.innerHTML + "<a href='#' onclick='closePicture()'>Close</a>";
    div.id = "bigpicture";
    div.style.display = "none";
    document.body.appendChild(div);
    Effect.Grow("bigpicture");
}

This is the basic function. It takes three arguments, just like the link. First, the variable image is set to the element with the id of “images” using the useful function $() from the prototype library. Also images gets all the <img> elements in the image <div>. Then each image is looped through using a for loop, first setting the variable i, while i is less than the amount of images in the array, and increasing i every loop. Then each image is methodically faded out.

After this, you need to create the image to see it. So the variable div is set to create a new element. Then div’s innerHTML is set to the title, the description, the image, and the close link. The id is set to bigpicture, and it is hidden, so that when it is introduced to the DOM tree it won’t be immediately seen and we can grow it in for coolness.

So, try out the effect. How does it look? Pretty cool? If you don’t like the effects, you can always change them.

Now you might want to be able to close that annoying gigantic box. So let’s do that now.


function closePicture(){
    Effect.Fade("bigpicture");

    var image = $("images");
    var images = image.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++){
        Effect.Grow(images[i])
    }
}

It’s an easy enough function. First it fades the box out. Then it’s just a matter of looping through the images again to grow them back.

The other part of this part of the gallery is: what if the user has javascript disabled? Well, then the link follows that action that was defined, “gallery.php?action=fullimage&id=anid”


        case "fullimage":
            $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
            $row = mysql_fetch_row($select);
            $id = $row[0];
            $title = $row[1];
            $description = $row[2];
            $image = $row[3];
            ?>
            <b><?=$title?></b>
            <p><?=$description?></p>
            <img src="<?=$image?>" alt="<?=$title?>" />
            <? 
        break;

It’s a pretty easy action. Just find the row and output the title, the description, and the image. It’s pretty basic.

Slideshow

Moving on to the final part of the gallery (and the most confusing): the slideshow.

Thinking about the slideshow, there has to be a way to loop through each image, defining each in the javascript somehow, and a timed action to show the next image.


        case "slideshow":
            $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
            $i = 1;
            echo "<div id='picture'>";
            while($r = mysql_fetch_array($select)){
                extract($r);
                if($i == 1){
                    echo "<b>$title</b>";
                    echo "<p>$description</p>";
                    echo "<img src='$image' alt='$title' />";
                    $i++;
                }
                else {
                ?>
                <script type="text/javascript">
                    slideshowarray('<?=$title?>', '<?=$image?>', '<?=$description?>');
                </script>
                <? 
                }
            }//end while
            echo "</div>";
            ?>
            <script type="text/javascript">
                setTimeout("slideshow()", 10000);
            </script>
            <? 
        break;//end slideshow

So that’s the basic idea. First you need to find each image, and loop through them. $i is defined as 1 so that the first image is not set in the javascript array. Then the first image is displayed. $i is then incremented, so that on the next image, it will be given into the function slideshow array. Then the <div> is closed (by the way, it was opened and defined with an id of picture), and the timeout is set for the next image. setTimeout takes two arguments: the first is the function, and the second is a number of milliseconds, 10000 being 10 seconds.

Now that that’s done, you need to actually have the slideshowarray function.


var slideshowr = new Array();

function slideshowarray(title, picture, description){
    slideshowr.push(new Array(picture, title, description));
}

This is the function. First, outside the function, is the variable slideshowr, which is an array. Make sure this is outside the array otherwise there will be a new array constantly.

Inside the function, which takes three arguments (title/picture/description), and pushes a new Array with the three arguments into the array.

Next is the slideshow function.


function slideshow(){
    var picture = $("picture");
    if(slideshowr.length >= 1){
    picture.innerHTML = "<b>"+slideshowr[0][1]+"</b>";
    picture.innerHTML += "<p>"+slideshowr[0][2]+"</p>";
    picture.innerHTML += "<img src='"+slideshowr[0][0]+"' alt='"+slideshowr[0][1]+"' />";
    slideshowr.reverse();
    slideshowr.pop();
    slideshowr.reverse();
    setTimeout("slideshow()", 10000);
    }
        else {
        picture.innerHTML += "<br />Slideshow has finished.<br />";
        picture.innerHTML += "<a href='gallery.php?action=slideshow'>Start Again?</a>";
    }
}

Now is the slideshow function.

First is the picture variable which is the DOM element with an id of “picture.” Then, if the slideshow array’s length is greater than or equal to 1, the variable picture’s innerHTML is set with the array’s values for the title, the description, and the image. The next is somewhat confusing. The function pop() usually takes the last entry off an array, but we need the first entry to be taken off. So the array is reversed, the last entry (which was the first) is popped off, then it’s reversed again to become like it was, but without that first entry. There was also another timeout set for the slideshow. And finally, if the array length is not greater than/equal to 1, then the picture <div> is updated to say the slideshow has finished.

Next Button

Now there’s one more feature of a slideshow that’s great: the next feature. You need to be able to get to the next picture easily. So update the setTimeout function and add this link near the bottom of the slideshow case.


<a href="#" onclick="slideshow(0); return false;">Next</a>
            <script type="text/javascript">
                setTimeout("slideshow(1)", 10000);
            </script>

The link adds an extra argument to the function, which will identify it as being the next button. And same with the setTimeout function.

Now to update the slideshow function.


function slideshow(link){
    var picture = $("picture");
    if(slideshowr.length >= 1){
    picture.innerHTML = "<b>"+slideshowr[0][1]+"</b>";
    picture.innerHTML += "<p>"+slideshowr[0][2]+"</p>";
    picture.innerHTML += "<img src='"+slideshowr[0][0]+"' alt='"+slideshowr[0][1]+"' />";
    slideshowr.reverse();
    slideshowr.pop();
    slideshowr.reverse();
    if(link != 0){
    setTimeout("slideshow()", 10000);
    }
    }
    else {
        picture.innerHTML += "<br />Slideshow has finished.<br />";
        picture.innerHTML += "<a href='gallery.php?action=slideshow'>Start Again?</a>";
    }
}

For all intents and purposes, it’s the same. The only exceptions is the link argument, and what goes with it. It’s all the same until one if statement: if the link does not equal 0 (meaning it was set regularly), then the setTimeout is still set. Otherwise, it won’t be set.

Image Gallery Conclusion

Now your whole image gallery is finished. Everyhing, javascript and everything.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Image Gallery</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="javascripts/prototype.js" type="text/javascript"></script>
<script src="javascripts/scriptaculous.js" type="text/javascript"></script>
<script type="text/javascript">
var slideshowr = new Array();

function bigImage(picture, title, description){
    var image = $("images");
    var images = image.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++){
        Effect.Fade(images[i])
    }

    var div = document.createElement("div");
    div.innerHTML = "<b>"+title+"</b>";
    div.innerHTML = div.innerHTML + "<p>"+description+"</p>";
    div.innerHTML = div.innerHTML + "<img src='"+picture+"' alt='"+title+"' /><br />";
    div.innerHTML = div.innerHTML + "<a href='#' onclick='closePicture()'>Close</a>";
    div.id = "bigpicture";
    div.style.display = "none";
    document.body.appendChild(div);
    Effect.Grow("bigpicture");
}

function closePicture(){
    Effect.Fade("bigpicture");

    var image = $("images");
    var images = image.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++){
        Effect.Grow(images[i])
    }
}

function slideshowarray(title, picture, description){
    slideshowr.push(new Array(picture, title, description));
}

function slideshow(link){
    var picture = $("picture");
    if(slideshowr.length >= 1){
    picture.innerHTML = "<b>"+slideshowr[0][1]+"</b>";
    picture.innerHTML += "<p>"+slideshowr[0][2]+"</p>";
    picture.innerHTML += "<img src='"+slideshowr[0][0]+"' alt='"+slideshowr[0][1]+"' />";
    slideshowr.reverse();
    slideshowr.pop();
    slideshowr.reverse();
    if(link != 0){
    setTimeout("slideshow()", 10000);
    }
    }
    else {
        picture.innerHTML += "<br />Slideshow has finished.<br />";
        picture.innerHTML += "<a href='gallery.php?action=slideshow'>Start Again?</a>";
    }
}
</script>
<style type="text/css">
* { 
    font-size: 14px;
    line-height: 150%; 
}
body { 
    font-family: Trebuchet MS, Verdana, Arial, sans-serif;
    background: url(gradient.jpg);
    background-repeat: repeat-x; 
}
h1 { 
    margin-left: 10em; 
}
h1 a {
    font-size: 1.75em;
}

#slideshow {
    margin-left: 5em;
    font-size: 1.5em;
}

/* Images */

#images {
    padding: 2em;
}

#images img {
    width: 150px;
    height: 150px;
    margin-right: 1em;
}

#bigpicture { 
    background-color:#CFDCE6;
    padding:2em;
    border:2px solid black;
}    
</style>
</head>
<body>
<h1><a href="gallery.php">Image Gallery</a></h1>
<h2>What We're About</h2>
<p>
    This was an image gallery that was conceived of, designed, and coded very quickly for a tutorial for the 
    <a href="http://www.shadow-fox.net">Shadow Fox Network</a> by <a href="http://blog.shadow-fox.net">Ben Hirsch.</a>
</p>

<a href="gallery.php?action=slideshow" id="slideshow">Full Slideshow</a><br /><br />

    <?php
    $connection = mysql_connect("localhost",
                            "username",
                            "password");
    mysql_select_db("database", $connection);

    switch($_GET["action"]){

        default:
        echo '<div id="images">';
        $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
        while($r = mysql_fetch_array($select)){
            extract($r);
            echo "<a href='gallery.php?action=fullimage&amp;id=$id' 
onclick=\"bigImage('".htmlspecialchars($image)."', '".htmlspecialchars($title)."', 
'".htmlspecialchars($description)."'); return false;\"><img src='$image' alt='$title' /></a>";
        }
        echo '</div>';
        break;//end default

        case "fullimage":
            $select = mysql_query("SELECT * FROM gallery WHERE id = ".$_GET['id']) or die(mysql_error());
            $row = mysql_fetch_row($select);
            $id = $row[0];
            $title = $row[1];
            $description = $row[2];
            $image = $row[3];
            ?>
            <b><?=$title?></b>
            <p><?=$description?></p>
            <img src="<?=$image?>" alt="<?=$title?>" />
            <? 
        break;

        case "slideshow":
            $select = mysql_query("SELECT * FROM gallery ORDER BY id DESC") or die(mysql_error());
            $i = 1;
            echo "<div id='picture'>";
            while($r = mysql_fetch_array($select)){
                extract($r);
                if($i == 1){
                    echo "<b>$title</b>";
                    echo "<p>$description</p>";
                    echo "<img src='$image' alt='$title' />";
                    $i++;
                }
                else {
                ?>
                <script type="text/javascript">
                    slideshowarray('<?=$title?>', '<?=$image?>', '<?=$description?>');
                </script>
                <? 
                }
            }//end while
            echo "</div>";
            ?>
            <a href="#" onclick="slideshow(0); return false;">Next</a>
            <script type="text/javascript">
                setTimeout("slideshow(1)", 10000);
            </script>
            <? 
        break;//end slideshow
    }//end switch
    ?>
<!---->
</body>
</html>

Tutorial Conclusion

There’s your whole image gallery. You’ve got the javascript, the images, the administration, it’s all there. Go and have fun with it.

Ideas For Extension

And here it is. Couldn’t miss it.

  1. Different Effects
  2. I’m sure not all the javascript libraries are needed
  3. Much better styling
  4. Image Size Limit
  5. Only a certain amount of images per page (with pagination)