• home
  • forum
  • my
  • kt
  • download
  • Complete Walkthrough: Creating a Gallery Class

    Author: 2008-08-26 11:09:20 From:

    This is my first tutorial actually. I'm not really even sure if I'm qualified to write tutorials, as I'm still learning PHP. But I think it will be a nice way for me to improove my PHP learning process, by explaining what I've done.

    So in this tutorial, we will create a gallery class, and also a template class that will work together with the gallery class.

    This is the structure of the files:

    | -> index.php
    |
    | -> includes
    |
    | - -> config.php
    |
    | - -> classes
    |
    | - - -> gallery.php
    |
    | - - -> template.php
    |
    | - -> templates
    |
    | - - -> index.tpl
    |
    | - - -> gallery.tpl
    |
    | - - -> view.tpl
    |
    | - - -> desc.xml
    |
    | -> img
    |
    | - -> folder.gif
    |
    | -> images
    |
    | - -> example folder 1
    |
    | - - -> 0.jpg
    |
    | - - -> 1.jpg
    |
    | - - -> 2.jpg
    |
    | - - -> 3.jpg
    |
    | - -> example folder 2
    |
    | - - -> 0.jpg
    |
    | - - -> 1.jpg
    |
    | - - -> 2.jpg
    |
    | - - -> 3.jpg



    So let's start!

    gallery.php
    Located in /includes/classes/gallery.php

    php Code:
    class gallery {
           
           
            // The total of everything.
            private $totalPages;
            private $totalPics;
            private $maxColumns;
            private $maxHeight;
            private $maxWidth;
           
            // The current value of everything.
            private $currentPicture;
            private $currentFolder;
            private $currentPage;
            private $currentPath;
            private $currentFolderPath;
            private $currentColumn = 1;
            private $currentSpan;
            private $currentFormat;
            private $currentXML;
            private $currentIndex;
                   
            // Arrays of available files.
            private $folders = array();
               
            // How many images shown per page in the gallery; set in config.php.
            private $imgPerPage;
           
            // The first of everything
            private $firstImage;
            private $firstPage = 1;
    I think this should be pretty self-explenatory.
    This is just basic variables that are needed.

    php Code:
    public function __construct($path) {
               
                if($handle = @opendir($path)) {
                   
                    $this->currentPath = $path;
                    closedir($handle);
                   
                }
               
                else {
                   
                    die('Could not open the image path '.$path.' <br />Please check your settings in the config.php');
                   
                }
               
               
            }
    This is the initializing function, that is required when you create the gallery object. What it does, is that it checks if it's able to open the image directory. If it can open it, it sets the currentpath variable to that value. If it can't open it, it dies, and echoes out that it can't open the directory.

    php Code:
    public function setImagesPerPage($imgPerPage) {
               
                $this->imgPerPage = $imgPerPage;
               
            }
           
            public function setIndex($index) {
               
                $this->currentIndex = $index;
               
            }
           
            public function setMaxCol($max) {
               
                $this->maxColumns = $max;
               
            }
           
            public function setSpan($span) {
               
                $this->currentSpan = $span;
               
            }
           
            public function setFormat($format) {
               
                $this->currentFormat = $format;
               
            }
           
            public function setXML($xml) {
               
                $this->currentXML = $xml;
               
            }
           
            public function setMaxWidth($width) {
               
                $this->maxWidth = $width;
               
            }
           
            public function setMaxHeight($height) {
               
                $this->maxHeight = $height;
               
            }
    These are just basic functions that sets the value of some variables.

    I wrote this script before I read about __call, so obviously, you can make this ALOT nicer and less code, by making a __call function for this.

    I might edit that later after I've written the tutorial, maybe ;)


    php Code:
    // Fetches the current value of $_GET['folder'] and sets the currentFolder to it.
            public function getFolder() {
                   
                $folder = $_GET['folder'];
           
                if($folder != "." && $folder != "..") {
                   
                    $this->currentFolder = $folder;
                   
                }
               
               
            }
    This function gets the value of the ?folder=VALUE in the URL.
    Ofcourse, the folder shouldn't be . or .., so we take those out.

    Now after reading more PHP tutorials, I've kind of realized that this isn't very safe either as they can still go up one directory and then go into another folder. So maybe you can come up with a nice preg_match function in this code piece, to take out all the dots if there exists.

    php Code:
    // Fetches the current value of $_GET['page'] and sets the currentPage to it.
            public function getPage() {
               
                $page = $_GET['page'];
                if (isset($page) && is_numeric($page)) {
                   
                    $this->currentPage = $page;
                   
                }
               
                else {
                   
                    $this->currentPage = 1;
                   
                }
               
            }
    Same as the function above, only that this checks for the current page.


    We now also have to check the value of the pic, by doing this:
    php Code:
    // Fetches the current value of $_GET['pic'] and sets the currentPicture to it.
            public function getPicture() {
               
                $pic = $_GET['pic'];
                if(is_numeric($pic)) {
                   
                    $this->currentPicture = $pic;
                   
                }
               
            }
    php Code:
    // Scans through the current image path, set in config.php, for folders.
            // If the folder set in $_GET['folder'] exists in the directory, the currentFolderPath is set to a value. Returns true or false.
            public function setPicFolder() {
               
                $folders = scandir($this->currentPath);
                foreach($folders as $folder) {
                   
                    if($folder != "..") {
                       
                        $this->folders[] = $folder;
                       
                    }
                   
                }
                $folderkey = array_search($this->currentFolder, $this->folders);
               
                if($folderkey) {
                   
                    $this->currentFolderPath = $this->currentPath.'/'.$this->folders[$folderkey].'/';
                    return true;
                   
                }
               
                else {
                   
                    return false;
                   
                }
               
                       
            }
    The first thing this function does, is scanning through the path that was needed when creating the gallery object.

    php Code:
    $folders = scandir($this->currentPath);
    The $folders will then be an array, so we foreach that array.
    If the folder in the current loop, is called "..", we don't include it.

    If it's anything else than "..", we put the name of that folder in the array $this->folders.


    After we've scanned through the directory, we do an array search.
    We search for $this->currentFolder (set in the $_GET['folder']), in the array $this->folders.

    If it finds it, we can set the currentFolderPath to
    php Code:
    $this->currentFolderPath = $this->currentPath.'/'.$this->folders[$folderkey].'/';
    This means, that if we're at ?folder=testing, the script would check in the folder /theimgpath/testing/ for images.


    The next function gets the total amount of pictures in the currentFolderPath:

    php Code:
    // Gets the total amount of pictures in the current folder.
            public function getTotalPics() {
               
                if ($handle = opendir($this->currentFolderPath)) {
       
                    while (false !== ($file = readdir($handle))) {
                   
                        if ($file != "." && $file != "..") {
                               
                            $this->totalPics++;
                                   
                        }
                               
                    }
                         
                    closedir($handle);
                   
                }
               
            }
    This function opens the directory of the folder specified in ?folder=
    Then it checks if false is not the same type as $file, if $file = readdir

    readdir reads through the directory, and loops through all of the files in it.
    If the file isn't called "." or "..", the variable $this->totalPics gets 1 value added to it.

    After the loop looped through all files, $this->totalPics would then contain the amount of all the pictures in the current folder.


    Now, I hope you're as smart as I am with maths(I'm just joking, I'm not very good >.< ), because there will be alot of maths from now on.

    php Code:
    // Gets the total amount of pages based on totalPics and imgPerPage.
            public function getTotalPages() {
               
                $totalPages = $this->totalPics / $this->imgPerPage;
                $this->totalPages = ceil($totalPages);
               
            }
    I think this is pretty straight forward.
    The total amount of pictures, is devided with how many images are allowed per page. We then get the amount of pages. But in order not to have like 11,6 pages.. we ceil it, meaning, round it up. So it would then be 12 pages instead of 11,6.

    We then set the $this->totalPages to the value of the total pages.

    php Code:
    // Gets the first image on whatever page the user is currently viewing.
            public function getFirstImage() {
               
                $this->firstImage = (($this->currentPage * $this->imgPerPage) - $this->imgPerPage);
               
            }
    This function, gets the first image, of the current page.

    So, let's say we have 10 images per page.
    On page 1, it would show the first 10 images.
    On page 2, it would show up to the (2 * 10)th image.

    With me so far?
    Page 1: 0-9
    Page 2: ?-19

    Now, we can pretty easy realize that the first image should be 10, on page 2. But in order for the script to get it, we need to subtract $imgPerPage from (2 * 10), leaving us with:

    (2 * 10) - 10 = 20 - 10 = 10


    Wow, even I didn't get my own explenation. But I hope you get it anyhow!
    Because we're moving on!!

    The next function isn't really the best coded function, but it gets the work done that it's supposed to!
    php Code:
    // Prints out a list of available folders.
            public function printFolders() {
               
                $folders = '
    <img src="img/folder.gif" /> <a href="'
    .$this->currentIndex.'">Index</a><br />
    '
    ;
               
                foreach($this->folders as $folder) {
                   
                    if($folder != "." && $folder != "..") {
                       
                        $totalPics = 0;
                        if ($handle = opendir($this->currentPath . $folder . '/')) {
       
                            while (false !== ($file = readdir($handle))) {
                   
                                if ($file != "." && $file != "..") {
                                   
                                    $totalPics++;
                                       
                                }
                               
                            }
                         
                            closedir($handle);
                   
                        }
                       
                        $folders .= '
    <img src="img/folder.gif" /> <a href="'
    . $_SERVER['PHPSELF'] . '?folder=' . $folder . '">' .$folder. '</a> ('.$totalPics.')<br />
    '
    ;
                       
                    }
                               
                }
               
                return $folders;
               
            }
    It loops through the array $this->folders, and checks how many pics in each folder.

    Then it just makes a nice link, with a folder image. The rest of the function is pretty self-explenatory, messy, but easy to understand.


    php Code:
    public function getFolders() {
               
                $count = count($this->folders);
               
                if($count == 1) {
                   
                    $msg = 'There are no folders in the gallery yet!';
                   
                }
               
                return $msg;
               
            }
    Pretty basic. It counts the array $this->folders, and if the count returns only 1, then it's no folders in the gallery.

    Returns that message.


    The next function, is getting the page links. This is REALLY hard to explain. I don't even know how to begin.
    The function itself is also very long. I'll take it in parts.
    Here is the whole function:

    php Code:
    // Prints out the links to the pages in the current folder.
            public function printPageLinks() {
               
                if($this->totalPics > 1) {
                   
                    if(($this->currentPage - ($this->currentSpan-1)) > $this->firstPage) {
                       
                        $links = '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->firstPage.'">
                        << '
    .$this->firstPage.'</a> .. ';
                       
                    }
                   
                    // Prints a list of available pages
                    for ($i = ($this->currentPage-($this->currentSpan-1)); $i <= ($this->currentPage+($this->currentSpan-1)); $i++) {
           
                           // If it's not too low, and not too high
                           if (($i >= $this->firstPage) && ($i <= $this->totalPages)) {
                       
                            // Show it
                             $links .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$i.'">';
                            $links .= ($i == $this->currentPage) ? ("<b>" .$i . "</b>") : $i ;
                            $links .= '</a> ';
           
                           }
                       
                    }
                   
                    if(($this->currentPage + ($this->currentSpan-1)) < $this->totalPages) {
                       
                        $links .= ' .. <a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->totalPages.'">
                        '
    .$this->totalPages.' >></a>';
                       
                    }
                   
                    $links .= '<br /><br />';
                   
                    // Back page link
                    if($this->currentPage > 1) {
                   
                        $links .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page=' .($this->currentPage-1). '">
                        Previous Page</a> '
    ;
                   
                    }
                   
                    // Next page link
                    if($this->currentPage+1 <= $this->totalPages) {
                   
                        $links .= ' <a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page=' .($this->currentPage+1). '">
                        Next page</a>'
    ;
                   
                    }
               
                    $links .= '<br />';
               
                }
               
                else {
                   
                    $links .= 'There are no images in this folder yet!';
                   
                }
               
                return $links;
               
            }
    php Code:
    public function printPageLinks() {
               
                if($this->totalPics > 1) {
                   
                    if(($this->currentPage - ($this->currentSpan-1)) > $this->firstPage) {
                       
                        $links = '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->firstPage.'">
                        << '
    .$this->firstPage.'</a> .. ';
                       
                    }
    It first checks if the totalPics is more than one, because otherwise there's no pictures in that folder.

    Then it checks if the current page, minus (current span - 1), is larger than the firstpage.

    The firstpage, is always 1.
    If the currentpage, is 5, and the span is set to 3.

    It will then check if 5 - (3 - 1 = 2) > 1 and that is simplified like the following:
    5 - 2 = 3
    if 3 > 1, which it is, it will print a link to the first page.

    So even if you're at page 10, and the span is set to 3:

    7 8 9 10 11 12 13

    It will show a link to the first page:

    << 1 .. 7 8 9 10 11 12 13


    Jesus, how will this tutorial continue... :confused::confused: Hard to explain maths :S

    Anyways.
    php Code:
    // Prints a list of available pages
                    for ($i = ($this->currentPage-($this->currentSpan-1)); $i <= ($this->currentPage+($this->currentSpan-1)); $i++) {
           
                           // If it's not too low, and not too high
                           if (($i >= $this->firstPage) && ($i <= $this->totalPages)) {
                       
                            // Show it
                             $links .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$i.'">';
                            $links .= ($i == $this->currentPage) ? ("<b>" .$i . "</b>") : $i ;
                            $links .= '</a> ';
           
                           }
                       
                    }
    This piece prints out a list of all available pages in the current folder.

    php Code:
    $i = ($this->currentPage-($this->currentSpan-1))
    In the beginning of the for loop. we set the initializer to the current page, minus (span - 1).

    And the loop will run, as long as
    php Code:
    $i <= ($this->currentPage+($this->currentSpan-1))
    $i is less, or equal to the currentpage + (span - 1).

    And at the end of each loop, we add 1 to $i.


    php Code:
    if (($i >= $this->firstPage) && ($i <= $this->totalPages)) {
    If $i is higher, or equal to the firstpage, and if $i is less or equal to the totalpage(lastpage), it will do this:

    php Code:
    $links .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$i.'">';
    A basic link, but this is the key part about it:
    php Code:
    $links .= ($i == $this->currentPage) ? ("<b>" .$i . "</b>") : $i ;
    It runs an if statement, and checks if $i is equal to the current page. If it is, the text of the link, will be in bold. Otherwise, it will just be the number.

    The last line in the loop I don't think I have to explain. It just closes the link.

    php Code:
    if(($this->currentPage + ($this->currentSpan-1)) < $this->totalPages) {
                       
                        $links .= ' .. <a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->totalPages.'">
                        '
    .$this->totalPages.' >></a>';
                       
                    }
    This is the same as the "first page" check, but this is the "last page" check.

    if the span is set to 3, and we're on page 1 of 20.
    It will echo: 1 2 3 4 .. 20 >>

    And if we're at the page 10, as the previous example:
    It will echo: << 1 .. 7 8 9 10 11 12 13 .. 20 >>


    Pretty neat huh? :D

    Next thing, we just echo out some basic breaklines, and then this:
    php Code:
    // Back page link
                    if($this->currentPage > 1) {
                   
                        $links .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page=' .($this->currentPage-1). '">
                        Previous Page</a> '
    ;
                   
                    }
    If the currentpage is higher than 1, it will echo out a "Previous Page" link.
    So the number link menu, is more if you wanna jump several pages at the time. And the "previous page" link will be for those who wanna scan through all the pages.

    php Code:
    // Next page link
                    if($this->currentPage+1 <= $this->totalPages) {
                   
                        $links .= ' <a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page=' .($this->currentPage+1). '">
                        Next Page</a>'
    ;
                   
                    }
    Same as the previous code piece. Only that this checks if the next page is less or equal to the last page. It will then echo out "Next page".

    Whoa! That was one long function. And messy. But hopefully, you'll just grasp the idea of this class, and will probably come up with your own solutions for some of the things here!

    The next function, prints out the actual images in the current folder.
    This function really deserves a whole topic of its own, because it's so much code!! :eek:


    php Code:
    // Prints out the images on the current page in the current folder.
            public function printImages() {
               
                $images = '<table border="1" cellpadding="5"><tr>';
           
                for($i = $this->firstImage; $i < ($this->firstImage + $this->imgPerPage); $i++) {
           
                    if (file_exists($this->currentFolderPath . $i . $this->currentFormat)) {
               
                        if($this->currentColumn >= $this->maxColumns) {
                           
                           
                            $xmlstring = simplexml_load_string(file_get_contents($this->currentXML));;               
                            foreach($xmlstring as $folder => $pic) {
                               
                                if($pic['folder'] == $this->currentFolder) {
                                   
                                    if($pic['id'] == $i) {
                               
                                        $title = $pic['title'];
                                   
                                    }
                                   
                                }

                            }
                           
                            $image = $this->currentFolderPath . $i . $this->currentFormat;
                            $images .= '<td><a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->currentPage.'
                            &pic='
    .$i.'" border="0" title="'.$title.'"><img src="'.$image.'" height="'.$this->maxHeight.'" border="0" /></a></td></tr><tr>';
                       
                            $this->currentColumn = 1;
                   
                        }
               
                        else {
                           
                           
                            $xmlstring = simplexml_load_string(file_get_contents($this->currentXML));;               
                            foreach($xmlstring as $folder => $pic) {
                               
                                if($pic['folder'] == $this->currentFolder) {
                                   
                                    if($pic['id'] == $i) {
                               
                                        $title = $pic['title'];
                                   
                                    }
                                   
                                }

                            }
                           
                       
                            $image = $this->currentFolderPath . $i . $this->currentFormat;
                            $images .= '<td><a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->currentPage.'
                            &pic='
    .$i.'" border="0" title="'.$title.'"><img src="'.$image.'" height="'.$this->maxHeight.'" border="0" /></a></td>';
                   
                            $this->currentColumn++;
                   
                        }
               
                    }
               
                }
           
                $images .= '</tr></table>';
                return $images;
               
            }
    Okey!, so let's try to explain this major HUGE function. Messy.. but still gets the work done ;) lol..

    php Code:
    for($i = $this->firstImage; $i < ($this->firstImage + $this->imgPerPage); $i++) {
    A basic for loop. Sets $i to the first image on the current page.
    And as long as $i is less then the first image + imgPerPage, it should do the loop.
    And at the end of each loop, it should add 1 to $i.

    php Code:
    if (file_exists($this->currentFolderPath . $i . $this->currentFormat)) {
    If the file exists in the folderPath, example: images/testing/2.jpg

    php Code:
    if($this->currentColumn >= $this->maxColumns) {
    If the current column is larger, or equal to the max columns allowed.

    php Code:
    $xmlstring = simplexml_load_string(file_get_contents($this->currentXML));;               
                            foreach($xmlstring as $folder => $pic) {
                               
                                if($pic['folder'] == $this->currentFolder) {
                                   
                                    if($pic['id'] == $i) {
                               
                                        $title = $pic['title'];
                                   
                                    }
                                   
                                }

                            }
    Gets the XML file for descriptions.
    Foreaches it, and if the folder id in the XML file is the same as the current folder, we check if the id is the same as the $i (pic id).
    We then set the $title to the value of the title="value" found in the XML file.

    php Code:
    $image = $this->currentFolderPath . $i . $this->currentFormat;
                            $images .= '<td><a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->currentPage.'
                            &pic='
    .$i.'" border="0" title="'.$title.'"><img src="'.$image.'" border="0" /></a></td></tr><tr>';
                       
                            $this->currentColumn = 1;
    This just gets a link to the image.
    At the end, we reset the currentcolumn to 1.

    php Code:
    else {
    If the currentcolumn is not larger than, or equal to maxcolumn, we do whatever's inside this bracket.

    First we just do the XML thing again, and gets the title from it.

    We then get the same link as before.
    The difference is at the end, where we don't start a new <tr>

    Also, we add one value to the currentcolumn.

    After the loop, we end the <tr> and the <table>.
    Then we return $images.

    I then have some really bad coded functions, but I'm too lazy to rewrite them.

    php Code:
    public function is_set($variable) {
               
                if($variable == 'folder') {
                   
                    return isset($this->currentFolder);
                   
                }
               
                elseif($variable == 'pic') {
                   
                    return isset($this->currentPicture);
                   
                }
               
            }
           
            public function getValue($variable) {
               
                if($variable == 'folder') {
                   
                    return $this->currentFolder;
                   
                }
               
                elseif($variable == 'pic') {
                   
                    return $this->currentPicture;
                   
                }
               
            }
    I'm not even going to explain those, because I think you'll get the point.


    Whoa, after reading through the next function, I realize that this function that's comming up, is far more longer, than the printImages().

    php Code:
    // Checks which picture the user is currently viewing and prints out the image.
            public function printImage() {
               
                if($this->is_set('pic')) {
                   
                    $img = $this->currentFolderPath . $this->currentPicture . $this->currentFormat;
                   
                    if(!file_exists($img)) {
               
                        $image .= '<br /><br /><br /><br />';
                        $image .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->currentPage.'">
                        Back</a><br /><br />'
    ;
                        $image .= 'This picture does not exist!';
                        $image .= '<br /><br /><br /><br />';
                   
                    }
               
                    else {
                   
                        $image .= '<a href="'.$_SERVER['PHPSELF'].'?folder='.$this->currentFolder.'&page='.$this->currentPage.'">
                        Back</a><br />'
    ;
                       
                        if(($this->currentPicture - 1) < $this->firstImage) {
                           
                            $nextImage = $this->currentFolderPath . ($this->currentPicture - 1) . $this->currentFormat;
                            if(file_exists($nextImage)) {
                               
                                $image .= '<a href="' .$_SERVER['PHPSELF']. '?folder='.$this->currentFolder.'&page='
                                .($this->currentPage - 1). '&pic=' .($this->currentPicture - 1). '">Previous Picture</a> ';
                               
                            }
                           
                        }
                       
                        else {
                           
                            $nextImage = $this->currentFolderPath . ($this->currentPicture - 1) . $this->currentFormat;
                            if(file_exists($nextImage)) {
                               
                                $image .= '<a href="' .$_SERVER['PHPSELF']. '?folder='.$this->currentFolder.'&page=' .$this->currentPage. '
                                &pic='
    .($this->currentPicture - 1). '">Previous Picture</a> ';
                               
                            }
                           
                        }
                       
                        $maxImage = ($this->currentPage * $this->imgPerPage);
                        if(($this->currentPicture + 1) >= $maxImage) {
                           
                            $nextImage = $this->currentFolderPath . ($this->currentPicture + 1) . $this->currentFormat;
                            if(file_exists($nextImage)) {
                               
                                $image .= '<a href="' .$_SERVER['PHPSELF']. '?folder='.$this->currentFolder.'&page='
                                .($this->currentPage + 1). '&pic=' .($this->currentPicture + 1). '">Next Picture</a>';
                               
                            }
                           
                        }
                       
                        else {
                           
                            $nextImage = $this->currentFolderPath . ($this->currentPicture + 1) . $this->currentFormat;
                            if(file_exists($nextImage)) {
                               
                                $image .= '<a href="' .$_SERVER['PHPSELF']. '?folder='.$this->currentFolder.'&page=' .$this->currentPage. '
                                &pic='
    .($this->currentPicture + 1). '">Next Picture</a>';
                               
                            }
                           
                        }
                        $image .= '<table border="1" cellpadding="10">';
                        list($width, $height, $type, $attr) = getimagesize($img);
                        $image .= '<tr><td>';
                        if($width > $this->maxWidth) {
                           
                            $image .= '<a href="'.$img.'" target="_blank">';
                            $image .= '<img src="'.$img.'" width="'.$this->maxWidth.'" height="'.$this->maxHeight.'" ';                       
                            $image .= 'style="cursor: pointer" title="Click for original size!" ';
                           
                        }
                        else {
                           
                            $image .= '<img src="'.$img.'" ';
                           
                        }
                       
                        $image .= 'border="0" />';
                       
                        if($width > $this->maxWidth) {
                           
                            $image .= '</a>';
                           
                        }
                        $image .= '<br />';
                       
                        $xmlstring = new SimpleXMLElement($this->currentXML, null, true);               
                   
                        foreach($xmlstring as $folder => $pic) {
                               
                            if($pic['folder'] == $this->currentFolder) {
                                   
                                if($pic['id'] == $this->currentPicture) {
                               
                                    $image .= '<center>' . $pic['info'] . '</center>';
                                   
                                }
                                   
                            }

                        }   
                       
                        $image .= '</td></tr></table>';
                   
                    }
                   
                }
               
                return $image;
               
            }
    First, we check if the pic id is set in the URL.
    If it is, we check if it exists.

    If it doesn't, we echo out an error msg!
    Pretty straight forward..

    php Code:
    else {
    If the image does exist!

    First we just print a link back to the page in the folder they were previously viewing.

    This is a bit tricky:
    php Code:
    if(($this->currentPicture - 1) < $this->firstImage) {
    If the currentpicture - 1, is less than the first image on the current page, we need to link them back one page in the URL.

    so..
    index.php?folder=test&page=3&pic=20
    the previous picture, must have:
    index.php?folder=test&page=2&pic=19

    If you get what I mean, so that's why we need 2 different links for previous pic.

    We check if the nextimage exists:
    php Code:
    $nextImage = $this->currentFolderPath . ($this->currentPicture - 1) . $this->currentFormat;
    php Code:
    if(file_exists($nextImage)) {
    Then we get the link.

    The code in the "else" brackets, is the same as the one in the if, except for this:

    if
    php Code:
    page='.($this->currentPage - 1).'
    else
    php Code:
    page='.$this->currentPage. '
    See the difference? ;)

    The rest is the same.


    The next piece of code decides the next pic link.

    php Code:
    $maxImage = ($this->currentPage * $this->imgPerPage);
    First we get the max image id on the currentpage.

    php Code:
    if(($this->currentPicture + 1) >= $maxImage) {
    Then we check if the current pic + 1 is larger than, or equal to the max image id.

    After that we basicly do that same thing we did with the previous pic link.
    We get the path to the pic, we check if it exists, and then we get the <img> link for it.

    Also, notice the difference between the code within the if brackets, and the code within the else brackets.
    And notice the difference between these, and the ones for the previous pic link.

    We then start a basic table, pretty easy.
    php Code:
    list($width, $height, $type, $attr) = getimagesize($img);
    This is pretty neat, because now we can get the actual size in width and height of the current pic.

    php Code:
    if($width > $this->maxWidth) {

    Here we check if the width of the pic is larger than the maxwidth.
    If it is, we add a link to the original picture.
    And we also resize it because we don't want the full size of the picture to cover up the whole screen.

    If it's not larger than the maxwidth, we just get the normal image.

    Then we close the image tag, with a border set to 0.
    And if the width was larger than max width, we close the link aswell.


    After that we do the XML thing again, and checks for the string in the XML file, that matches foldername, pic id, and get the info from that pic.

    We then close the table, and then return all of that.

    I'm not gonna go in-depth with this class, because there's already a tutorial for this class!

    php Code:
    class template {

       
            private $template_dir = 'includes/templates/';
            private $file_ext = '.tpl';
            private $buffer;
           
       
            public function load($file) {
       
                if(file_exists($this->template_dir . $file . $this->file_ext)) {
       
                    $this->buffer = file_get_contents($this->template_dir . $file . $this->file_ext);
                    return $this->buffer;
       
                }
       
                else {
       
                    echo $this->template_dir . $file . $this->file_ext . ' does not exist';
       
                }
       
            }
       
            public function output($input, $array) { 
       
                $search = preg_match_all('/{.*?}/', $input, $matches);
       
                for($i = 0; $i < $search; $i++) {
       
                    $matches[0][$i] = str_replace(array('{', '}'), null, $matches[0][$i]);
       
                }
       
                foreach($matches[0] as $value) {
       
                    $input = str_replace('{' . $value . '}', $array[$value], $input);
       
                }
       
                echo $input;
       
            }

         }
    This is pretty easy to understand.

    php Code:
    // The path to the image folder.
        $path = 'images/';
       
        // What format is all the pictures.
        $format = '.jpg';
       
        // How many pictures per row on each page.
        $maxcol = 2;
       
        // How many pictures per page.
        $imgPerPage = 8;
       
        // Name of the XML file which holds all the description data of all pictures.
        $xml = 'includes/templates/desc.xml';
       
        // Sets the max height for images in gallery view.
        $maxHeight = 200;
       
        // Sets the max width for images in image view.
        $maxWidth = 700;
       
        // How many pages to display in each direction IF they exists.
        $span = 3;
       
        // Set this to whatever name you have on the gallery index page.
        $index = 'index.php';
    That is the editable variables in the config.

    The next part of the config, is just setting things up with the class:
    php Code:
    // Includes the class file.
        include('classes/gallery.php');
       
       
        // Creates a new object from the class.
        $gallery = new gallery($path);
       
        // Sets the format of all pics.
        $gallery->setFormat($format);
       
        // Sets the index page.
        $gallery->setIndex($index);
       
        // Sets how many images per page.
        $gallery->setImagesPerPage($imgPerPage);
       
        // Sets how many images per row.
        $gallery->setMaxCol($maxcol);
       
        // Sets max height in gallery view.
        $gallery->setMaxHeight($maxHeight);
       
        // Sets the max width in image view.
        $gallery->setMaxWidth($maxWidth);
       
        // Sets the span.
        $gallery->setSpan($span);
       
        // Sets the XML file.
        $gallery->setXML($xml);   

       
        // Includes the class file.
        include ('classes/template.php');
       
        // Creates a new object from the class.
        $tpl = new template;
    Pretty easy to understand.. it just creates the object, and sets some variables in the class.
    desc.xml
    Located in /includes/templates/desc.xml

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <folder>
        
    -------foldername 1--------------------------------------
        
            <pic id="0" folder="foldername 1" info="Testing0" title="bla" />
            <pic id="1" folder="foldername 1" info="Testing1" title="test" />
            <pic id="2" folder="foldername 1" info="Testing2" title="testing" />
            <pic id="3" folder="foldername 1" info="Testing3" title="test" />
            <pic id="4" folder="foldername 1" info="Testing4" title="Testing more" />
            <pic id="5" folder="foldername 1" info="Testing5" title="testing title" />
            
    -------foldername 2--------------------------------------
            
            <pic id="0" folder="foldername 2" info="Testar" title="testar title" />
            
    </folder>
    This is the structure of the XML file.

    The long lines with "-" is not neccessary, but it does make it easier to find certain folders if you have alot of folders.

    Pretty self-explenatory.
    id: The id of the picture
    folder: The foldername where this picture is located
    info: The text that will appear below the picture when you view only that pic.
    title: This is the text that will appear when you hover the picture in the gallery.
    template.tpl
    Located in /includes/templates/templatename.tpl

    index.tpl

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <meta name="author" content="Tanax">
    
        <title>{title}</title>
    </head>
    
    <body>
    {folders}
    
    <center>
    {content}
    </center>
    
    
    </body>
    </html>
    view.tpl

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <meta name="author" content="Tanax">
    
        <title>{title}</title>
    </head>
    
    <body>
    {folders}
    
    <center>
    {image}
    </center>
    
    </body>
    </html>
    gallery.tpl

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <meta name="author" content="Tanax">
    
        <title>{title}</title>
    </head>
    
    <body>
    {folders}
    
    <center>
    {pagelinks}
    {images}
    </center>
    
    </body>
    </html>
    It's pretty basic! But this is how it looks. You can change where the pagelinks are shown, etc etc.. by just changing the order of them in the html code.
    Index.php
    Located in root folder

    So finally, the last piece of script!
    The script that pulls everything together, and uses all the classes and everything!

    Let's see how it looks:

    PHP Code:
        include('config.php');
        
        
    // Loads the default HTML page.
        
    $page $tpl->load('index');
        
        
    // Initiate the array of content.
        
    $array = array();
        
        
    // Gets the current folder from the URL.
        
    $gallery->getFolder();
        
        
    // Gets the current page from the URL.
        
    $gallery->getPage();
        
        
    // Gets the current picID from the URL.
        
    $gallery->getPicture();
        
        
    // Sets the folder to load picture from, based on what the current folder is set in the URL.
        
    $gallery->setPicFolder();
        
        
    // Gets the total amount of pictures from the current picFolder.
        
    $gallery->getTotalPics();
        
        
    // Gets the total amount of pages based on how many pictures there exists in the picFolder.
        
    $gallery->getTotalPages();
        
        
    // Gets the first image on the current page based on what page the user is viewing.
        
    $gallery->getFirstImage();
        
        
    // Gets the folder links.
        
    $totalFolders $gallery->printFolders();
        
        
    // Checks if there isn't any folders.
        
    $noFolders $gallery->getFolders();
        
        
    // Assigns the key "folders" the value of the returned value from the folder links.
        
    $array['folders'] = $totalFolders;
        
        
    // If the user is viewing the index.
        
    if(!$gallery->is_set('folder')) {
            
            
            
    $content 'Welcome to the gallery! Click on one of the folders to the left in order to view the images!';
            
    $content .= $noFolders;
            
    $array['title'] = 'Gallery | Index';
                    
        }
        
        
    // If the user is viewing the gallery.
        
    elseif(!$gallery->is_set('pic')) {
            
            
            
    $pages $gallery->printPageLinks();    
            
    $images $gallery->printImages();

            
    $array['title'] = 'Gallery | ' .$gallery->getValue('folder');    
            
    $page $tpl->load('gallery');


        }
        
        
    // If the user is viewing a picture.
        
    elseif($gallery->is_set('pic')) {
                
            
            
    $image $gallery->printImage();
            
            
    $array['title'] = 'Gallery | ' .$gallery->getValue('folder'). ' | Picture ' .$gallery->getValue('pic');
            
            
            
    $page $tpl->load('view');
                
        }
        
        
        
    // Assigns values in the array.
        
    $array['image'] = $image;
        
    $array['pagelinks'] = $pages;
        
    $array['images'] = $images;
        
    $array['content'] = $content;
        
        
    // Outputs the page.
        
    $tpl->output($page$array); 
    First thing we do, is include our config file. We then load the index.tpl file for our template.

    After that we set a bunch of variables. You should be able to read the comments in the code to see what they do.

    Actually, everything is pretty explained in the code.
    Just read the comments.

    One thing though. We do not parse the site until the very end of the script.
    Because if the user is viewing a gallery, we load another file instead of the index.tpl.
    And if they're viewing an image, we load another file.

    Also one other thing!
    You can see, $image variable only exists if the user is viewing a special picture. But we still assign that to the $array in the end, and outputs it with the loaded file.

    The way it works is, that if the value is empty, it won't echo out anything, and we haven't included {image} in any other .tpl file than the one the viewer is using when viewing a specific picture, which is view.tpl



    I really hope you've learned something about at least something.
    It's really a MAJOR tutorial, and probably most of you won't bother reading through the whole thing.

    But if you do read through it, maybe you can come up with a way so the functions in the gallery class only returns DATA, and no actual HTML output. And then you can decide exactly how to format the things, within the templatefiles.

    But that's for you to figure out!


    NOTE!
    The images in the different folders, have to be named in numeric order, such as:
    0
    1
    2
    3
    4
    5

    The fileformat can be other than .jpg, but all images must have same fileformat!
    You can just edit the fileformat in the config.php


    Signing out, hope you had a nice read.
    Thanks
    // Tanax
    Attached Files
    File Type: phpgallery.php (16.5 KB, 209 views)
    File Type: phptemplate.php (1.1 KB, 165 views)
    File Type: phpconfig.php (2.1 KB, 159 views)
    File Type: xmldesc.xml (679 Bytes, 154 views)
    File Type: phpindex.php (2.4 KB, 193 views)

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (11)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (13)
      Error Handling (7)
      File Manipulation (24)
      Flash and PHP (6)
      Form Processing (19)
      Guestbooks (12)
      Image Manipulation (21)
      Installing PHP (7)
      Introduction to PHP (23)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot