How to update an HTML image gallery (PHP tutorial)

In this tutorial I’ll walk you through the steps involved in building a databaseless PHP admin section for Smooth Gallery. When done, without much effort you should be able to adapt the code to fit any similar JavaScript image gallery(/slider/switcher/swapper… whatever). So let’s take a look at it:

Smooth Gallery Manager

Smooth Gallery Manager

As mentioned on the manager page, the password is “demo” and you don’t have sweat about removing/adding/reordering images—the manager in the demo resets the file to an initial input each time a user logs in. For faster testing: right click some photo from the internet, select copy image location and paste it in the Add New Item/Image location field (that’s the only required field). Then press Add. Then in the Edit Items part copy and paste image locations from one item to another and then update it.

You will want to download the gallery + manager before continuing. After you do, open up manager.php and follow along. Only the more important parts ware discussed below, the rest is commented in the file.

So how come no databases?

It’s an image gallery, it’s not gonna have thousands of entries. There’s not much justification in creating a database for 5-20 items. We’ll keep it all in the HTML. And this will give us a chance to work with a really neat tool: PHP Simple HTML DOM Parser. This HTML parser written in PHP5+ is going to save us a lot of work. And I think this won’t be the last you hear of it here on Vile Works.

1. The logic behind it, in plain English

We’re going to have a simple log in/log out functionality, we don’t want anyone who knows the manager’s URI to be able edit our gallery. After the log in, two main options will be available: add new item and edit existing items. …And a log out link.

if logged in
	if received 'add item'
		add the item;
	display 'add item' form;
	if received 'update items'
		update all the items;
	display 'update items' form;
	display 'log out' link;
else
	display 'log in' form;

The conditioned actions “if received ‘add item’ -> add the item” and “if received ‘update items’ -> update the items” are placed in the code before their forms so that they will display a success or error message in the page just above the form that was submitted. The “add new item” functionality will add a new item at the beginning of the gallery: the image along with its title, description and a link to another page. The “update items” will allow us to:

  • change the items’ titles, descriptions, images and the URL the images link to
  • delete items
  • and to reorder the items

2. What’s the manager managing

Let’s take a look at the HTML code of a regular SmoothGallery. And this is a kind of a common way for JavaScript image galleries to store their data in the HTML although some might have small differences like using <li>;’s instead of <div>’s for the item nodes (which I believe is a more semantic way). Note: The default Smooth Gallery also had a carousel displaying thumbnails of images. To keep things more general (and not just Smooth Gallery specific), the thumbnails will not be handled by the manager—they were also removed from the HTML—and the carousel was turned off in jd.gallery.js:

showCarousel: false,

However, after getting an idea about how the whole thing works, through a small process of intuition the specific functionality could be easily added.

3. Using the Simple HTML DOOM Parser to add a new element

The “add new item” action will just add a new HTML node at the beginning of the gallery with the inputted details it received from the form. The above snippet is just the part responsible for the “add new item” action. And this is where the HTML parser first comes in.

$temp_item->find('img',0)->src

Those of you familiar with the jQuery JavaScript library might have noticed the find() method. This searches for all descendant elements that match the specified expression (CSS selector). In the code above, the second argument for the find() method is the element’s index—in our case 0, because we always need the first (and only) match. After getting to an element, you can easily manipulate its attributes (src, href etc) and its inner and outer text. The image below illustrates the difference between the innertext and outertext. innertext/outertext

Outer text is the element including its opening and closing tags and the inner text is just what’s “inside” of it, between the opening and closing tags. What follows in the code is the HTML for the form which sends the data to the snippet discussed above.

4. Using the Simple HTML DOOM Parser to update the existing elements

And by “update” I mean edit, delete or reorder.

4.1 Updating and deleting

In the first loop we’re going through the items and if an item was deleted, the outer text is set to null and its position is stored in the $deleted_positions array (we’ll need these positions when we sort them). If the item wasn’t deleted, all its information will be updated.

4.2 Sorting the items with Bubble sort

The do…while loop in the snipped above uses the Bubble sort method to sort the items by positions. As mentioned in the comment, besides the actual item swap we also need to do an swap for the positions, since these aren’t connected to the items—they’re just stored in the $positions array. Followed by the form with all the options for each image. This is where the updates are sent from to the snippet above. Nifty fact: Because of the way we’re using the positions, we’re able to enter any rational number as a position. So if you wanted to put the last image on the 2nd position, you’d just have give it a position of 1.5 (or anything between 1 and 2), instead of giving it 2 and changing the position for the second to 3 and for the 3rd to 4 and so on. And after pressing submit, the order is achieved and the positions are nice natural numbers again. Because we just want two items per row we’re checking if the position is an even (if ($position%2 == 0)) and if it is we’re adding some class for the CSS to handle and an horizontal ruler.

Conclusions

So this pretty much covers the PHP part. I commented as much as I could of the code but still, feel free to shoot any questions in the comments. Of course, the view needed some CSS stylying for a decent display. The Blueprint CSS framework was used for faster and cleaner development. And some more JavaScript (mootools to be more precise) improvements made their way in, achieving tasks like:

  • select all text when clicking in a text field
  • instantly change the displayed image when the text in the image location is changed
    • and this means the Reset button now has to reset back all the images and not just the fields

So that’s about it. Hope the effort invested was worth it and the result was of help to you. For those of you interested, there’s a tutorial on Nettuts with a similar goal using PHP and mySQL:

For this lesson, our goal is to create a photo admin section where an administrator can retrieve photos from a database and update the title of his photos simply by clicking on the appropriate text.

Posted in blog Tagged with: , , , , ,
10 comments on “How to update an HTML image gallery (PHP tutorial)
  1. navi says:

    Since building my own version of this has been engraved on my to do list, I’ve been waiting for something like this for so long. Can’t wait to try it out.

  2. James McRoy says:

    This is a fantastic concept. Thanks for putting it together. As a newbie to php, I find I work best with cheat sheets. Since I always have my iPhone with me, I keep them there. The best one I’ve found so far is from these guys:

    http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=302760278&mt=8

    They also have great cheat sheets for CSS and Javascript. Hope this is helpful!

  3. Svante Karlsson says:

    I would like to know how to modify the admin so it can be used with more than one gallery. So you can have your gallery look like this http://smoothgallery.jondesign.net/showcase/gallery-set/ and still have an awesome admin!
    /Svante

  4. Stefan says:

    @Svante Karlsson:

    If you take a look at its source code you’ll see that the gallery’s HTML is very similar to the HTML of the gallery from my article. Only difference is the gallery set has multiple galleries in it.

    <div id="gallerySet">
        <div id="myGallery1" class="galleryElement">
              ....
        </div>
        <div id="myGallery2" class="galleryElement">
              ....
        </div>
    </div>
    
    

    The above is what a gallery set looks like. My gallery (from the tut) looks like this:

    <div id="myGallery" class="galleryElement">
        ....
    </div>
    

    So what you need to do is to send that gallery id (i.e. myGallery, or myGallery1, or myGallery2) to the php script in order to tell it what gallery to edit.

    In short, you have to change this line:

    $items = $html->find('#myGallery .imageElement')

    to this:

    $items = $html->find($_GET["gallery_id"] . ' .imageElement'); 

    (Just to make sure, check all the apostrophes and quotes, WordPress comments may have screwed ‘em up.)

    Then, when you access the php file, add at the end of its address ?gallery_id=myGallery1 or ?gallery_id=myGallery2 in order to pass it the correct parameter (I’m assuming you know how to send a value via GET).

    That should work, hope it makes sense.

  5. vlad says:

    Thanks Stefan for sharing your knowledge and work. I am stuck. I found the easiest way to insert link into slideshow on your demo but I am unable to execute the smooth gallery manager.php. Where I should upload it. I already tried upload it alone into plugins, into smooth gallery and I don’t see it in plugins neither in settings and editor. I just don’t have the knowing how. Can you please be of asistance. Thanks very much. Vladimir

  6. Stefan says:

    @vlad: From the downloaded archive you only need the file called “manager.php” and the “backend” folder.

    Place those two in the same folder as the gallery file.

    Edit “manager.php” and modify these two variables:

    $password=’demo’;

    $gallery_location=’index.html’;

    Hope this helps!

  7. vlad says:

    Thanks very much for the fast and useful reply. All the best. Vlad

  8. Geraldine says:

    I’ve been loionkg for a post like this forever (and a day)

  9. What if the gallery is not in a specific file? My gallery get called via /index.php?page=galerie.
    What do i have to set up in the manager.php?
    Tried
    $gallery_location=’index.php’;
    $gallery_location=’index.php?page=galerie’;
    $gallery_location=’galerie.twig’; (<- its the php framework)

    But non of them will work.

    Any idea?

    best regards
    denym

    • Stefan Matei says:

      Denny, by “not in a specific file” do you mean your gallery is in a database? If it’s in a database, this tutorial will not work for you since its whole premise is that we’re not using databases. If this is the case, the link to the Nettuts tutorial in my last paragraph might interest you.

      This manager only works if you have the gallery code in a flat HTML file. In your php code you could use < ?php include ('gallery.html'); ?> where the gallery needs to appear, and then put all the HTML for the gallery in that gallery.html file.
      In this case, $gallery_location would be ‘gallery.html’

      Hope this helps!

3 Pings/Trackbacks for "How to update an HTML image gallery (PHP tutorial)"
  1. [...] PHP Tutorial: Build a Backend Manager [...]

  2. Geek Week - This week jQuery tutorials, CSS3, & WordPress - PHP, XHTML, Web Design, Flash | JasonCypret.com says:

    [...] Build a Backend Manager for Smooth Gallery [...]

  3. PHP Tutorial: Build a Backend Manager for Smooth Gallery | CLD Tutorials - Web Design and Graphic Design Tutorials says:

    [...] View tutorial Difficulty : beginner Tutorial Stats : 1 views Rate Tutorial : (No Ratings Yet)  Loading … DiggStumbleDel.icio.usFloatBumpMixxRedditzaBoxother [...]