Currently Browsing: Home » Simple PHP Gallery Pagination

Simple PHP Gallery Pagination

In my previous article, Create a Simple Picture Gallery using PHP, KDM dropped me a nice comment about adding pagination.

In order to satisfy his needs (and our own), this post will present simple PHP gallery pagination. If you haven’t read the previous article, please refer back to it.

Pagination

View a Demo Download the Files

We’ll start with the previous code.

The first requirement is to split up getPictures() into multiple functions. The size of this large function makes it hard to edit the Simple PHP Gallery.

We can move the section that creates the thumbnail into a separate function, makeThumb($file, $type).

The new getPictures() is as follows:


	function getPictures() {
		if ( $handle = opendir(".") ) {
			$lightbox = rand();
			echo '<ul id="pictures">';
			while ( ($file = readdir($handle)) !== false ) {
				if ( !is_dir($file) && ($type = getPictureType($file)) != '') {
					if ( ! is_dir('thumbs') ) {
						mkdir('thumbs');
					}
					if ( ! file_exists('thumbs/'.$file) ) {
						makeThumb($file, $type);
					}
					echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
					echo '<img src="thumbs/'.$file.'" alt="" />';
					echo '</a></li>';
				}
			}
			echo '</ul>';
		}
	}

makeThumb($file, $type) is defined as:


	function makeThumb($file, $type) {
		global $max_width, $max_height;
		if ( $type == 'jpg' ) {
			$src = imagecreatefromjpeg($file);
		} else if ( $type == 'png' ) {
			$src = imagecreatefrompng($file);
		} else if ( $type == 'gif' ) {
			$src = imagecreatefromgif($file);
		}
		if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
			$newW = $oldW * ($max_width / $oldH);
			$newH = $max_height;
		} else {
			$newW = $max_width;
			$newH = $oldH * ($max_height / $oldW);
		}
		$new = imagecreatetruecolor($newW, $newH);
		imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
		if ( $type == 'jpg' ) {
			imagejpeg($new, 'thumbs/'.$file);
		} else if ( $type == 'png' ) {
			imagepng($new, 'thumbs/'.$file);
		} else if ( $type == 'gif' ) {
			imagegif($new, 'thumbs/'.$file);
		}
		imagedestroy($new);
		imagedestroy($src);
	}

It’s now time to add pagination. We should create another setting, $per_page, which will hold the number of images we’ll show per page.

The URL will use the format ?page=x, where x is the page number. In the PHP code, we’ll need to fetch this value using the $_GET[] array.


	# SETTINGS
	$max_width = 100;
	$max_height = 100;
	$per_page = 5;

	$page = $_GET['page'];

Now that we have the page number, we need a way of accessing the corresponding images.

To accomplish this, we should skip the files between 0 and the first image on that page. The amount to skip is the page number multiplied by the amount of images per page, assuming the first page is page 0.

The following code, which we will put directly before the main loop, does exactly this:


	$count = 0;
	$skip = $page * $per_page;

	while ( $count < $skip && ($file = readdir($handle)) !== false ) {
		if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
			$count++;
	}

Of course, the main loop needs to be modified to accompany this change:


	$count = 0;
	while ( $count < $per_page && ($file = readdir($handle)) !== false ) {

We must now give the user a way to navigate between pages.

We should add two variables, $has_previous and $has_next, that will deal with this problem. They will be used to add links in the HTML after <?php getPictures(); ?>:


<?php getPictures(); ?>

<?php
	if ( $has_previous )
		echo '<p class="prev"><a href="?page='.($page - 1).'">← Previous Page</a></p>';

	if ( $has_next )
		echo '<p class="next"><a href="?page='.($page + 1).'">Next Page →</a></p>';
?>

Originally, the two variables will be set to false:


	$has_previous = false;
	$has_next = false;

If $skip is not 0, then the user isn’t situated on the first page. Thus, $has_previous must be true:


	if ( $skip != 0 )
		$has_previous = true;

This must be added after $skip = $page * $per_page.

Next, $has_next should be set to true if there are any more image files. This snippet will be placed at the end of the function:


	while ( ($file = readdir($handle)) !== false ) {
		if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
			$has_next = true;
			break;
		}
	}

Thus, the final code is:


	function getPictures() {
		global $page, $per_page, $has_previous, $has_next;
		if ( $handle = opendir(".") ) {
			$lightbox = rand();
			echo '<ul id="pictures">';

			$count = 0;
			$skip = $page * $per_page;

			if ( $skip != 0 )
				$has_previous = true;

			while ( $count < $skip && ($file = readdir($handle)) !== false ) {
				if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
					$count++;
			}
			$count = 0;
			while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
				if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
					if ( ! is_dir('thumbs') ) {
						mkdir('thumbs');
					}
					if ( ! file_exists('thumbs/'.$file) ) {
						makeThumb( $file, $type );
					}
					echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
					echo '<img src="thumbs/'.$file.'" alt="" />';
					echo '</a></li>';
					$count++;
				}
			}
			echo '</ul>';

			while ( ($file = readdir($handle)) !== false ) {
				if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
					$has_next = true;
					break;
				}
			}
		}
	}

Have fun with your pagination. Until next time!

Tags: ,

This entry was posted on Saturday, March 21st, 2009 at 17:16:48. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

33 Responses to “Simple PHP Gallery Pagination”

  1. UntosCZ says:

    This gallery is so simple and so light!
    Great work!

  2. Gordan says:

    Hello Patrick,
    Is there a way to add to this script a php function which would read the description from a single text file – for each image in the gallery respectively, and then attach the description text to the corresponding image in the lightbox pop-up – by using the “title” tag. So that each image has its own corresponding description text beneath it.

    I’m very new to php, and I’ve been searching for this specific solution for days.

    thank you for any kind of reply
    best,

    • Hey Gordan,

      Patrick is away. I’ll answer your question. I made an example for you to look at. The PHP code is located here and the .txt file is here.

      Notice how I added a simple function and two lines of code. All the changes from the original file are bolded. It reads in description.txt in the following format:

      image file 1 (ex. image.jpg)
      description for image file 1 (ex. a waterfall)
      image file 2
      description for image file 2
      etc.

      and adds the description to the title tag of the corresponding image link.

      Feel free to comment if you have any more questions!

  3. Gordan says:

    Thank you Karthik, for your help so quickly! You guys are incredible

    best,

  4. arno says:

    A very good and usefull POST.
    Thanks !!!

  5. JMMR says:

    Hi.
    I’m looking your code and it’s great!!!!
    But I want to get the images in other folder. What changes I will do?
    Regards.

  6. veepee says:

    the gallery is listing the images according to the time stamp. is there a way to make it list the images by filename? 001.jpg, 002.jpg, etc?

    thx.

  7. Patrick Lin says:

    JMMR,
    I discussed this with a fellow by the handle of Deca on the predecessor to this article, Create a Simple Picture Gallery using PHP. You can read our discussion starting with Deca’s comment.

    Veepee,
    Your problem was covered in another article here, Reading directories in sequence in PHP.

    Patrick

  8. Johnnie says:

    I’m having trouble including the ‘Reading directories in sequence in PHP’ script with the ‘Simple PHP Gallery Pagination’ script.

    I can only manage to display all images with no pagination. Is there a complete script with both the ‘sequence’ and ‘pagination’ scripts together.

    Thank you!

  9. M&M says:

    Hi,

    Is there a way to display the thumbs on multiple rows? Right now all 5 are displayed in row 1, what if you wanted to do 3 on row 1, 3 on row 2, etc?

    Thanks!

  10. blueberrylolli says:

    Hi,

    Thanks for this awesome tutorial. I have a problem though, when I try to change the max_height/max_width the script is unresponsive. I changed the numbers to like 200, and 450, and the image thumbs still show up as 100 px wide. thanks for your help!

  11. Benny says:

    Heya,

    I’m using this simple script (thanks a lot!) but is there a way to instead of listing the old files first to list the newest? Right now it lists the oldest (or is that my server doing that?)

    Any help would be appriciated! I had a look over the “Reading directories in sequence in PHP” pages but that was no help at all for a beginner like me.

    Thanks :)

  12. Pogi says:

    Hello, thanks for this simple gallery with pagination. Is there a way you could make this a plugin for wordpress? I’m using wordpress, and I usually post a batch of icons in each post. Is there a way I could implement this into wordpress? Thanks again.

  13. ryan says:

    Here’s a simple image pagination that you don’t need to use Lightbox for…I never did get the above script to work…the directory gets image uploads only…

    <?
    $directory = “images/uploads/”;
    $filecount = count(glob(“” . $directory . “*.*”));
    //echo “THE TOTAL COUNT ” . $filecount . “”;

    $num_rows = 1;

    if($_GET['start']){
    $start = $_GET['start'];
    } else {
    $start = 1;
    }

    $prev_start = $start – $num_rows;
    $next_start = $start + $num_rows;

    //echo “prev_start: ” . $prev_start . “”;
    //echo “next_start: ” . $next_start . “”;
    if ($prev_start > 0) {
    echo ‘previous picture ‘;
    }

    if ($prev_start > 0 && $next_start <= $filecount) {
    echo ‘ | ‘;
    }

    if ($next_start <= $filecount) {
    echo ‘next picture‘;
    }
    echo ”   (” . $filecount . ” pix)” . ” ” . “\n” . “” . “\n”;
    $loopcount = 1;
    $handle = @opendir(“images/uploads/”);
    if(!empty($handle)) {
    while(false !== ($file = readdir($handle))) {
    if (strlen($file) > 4) {
    chmod(“images/uploads/” .$file, 644);
    if (($loopcount > ($start – 1)) && ($loopcount < ($start + $num_rows))) {
    echo “” . “\n”;
    echo ‘#’ .$loopcount . ‘‘ . “\n”;
    $imagecount++;
    }//end filecount loop
    $loopcount++;
    }//end strlen loop
    } //end while
    } //end emptyhandle loop

    echo “”;

    /*if(!empty($handle)) {
    while(false !== ($file = readdir($handle))) {
    if(is_file(“images/uploads/” . $file)) {
    chmod(“images/uploads/” .$file, 644);
    echo ‘‘;
    }
    }
    }*/

    closedir($handle);
    ?>

  14. 2desdes says:

    It`s possible to add an alphabetic file name ordering when linting the images?
    Thank you!

  15. Boris says:

    I am a nubi at php but have been looking for this function in a site I’m building … however I cannot add any includes, (footer, menu etc) if I add an include and can add some text characters within the body of the include, these characters are displayed but none of the gallery images can be seen.

  16. Boris says:

    I know this is an old question but I have recently been looking at the question of a function which would read the description of an image from a single text file. I saved the file as described: ‘description.txt’ and added the resulting file to the root, but still no result???

  17. milena says:

    lightbox doesnt work as it should, only half of the screen is black when zoom picture?? Does anyone had this problem???

  18. dman99 says:

    I saw some people asking if it were possible to have the newest results displayed first. This is exactly how I wanted it to function, so I rewrote the script using sort() and array. This will allow you to sort the pictures however you wish. All of my images were named with time(), so the larger the name, the newer the image.
    <?php
    # SETTINGS
    $max_width = 100;
    $max_height = 100;
    $per_page = 10;

    $page = $_GET['page'];

    $has_previous = false;
    $has_next = false;

    function getPictures() {
    global $page, $per_page, $has_previous, $has_next;
    if ( $handle = opendir(".") ) {
    $files = array();
    while ( ($file = readdir($handle)) !== false ) {
    $files[] = $file;
    }
    Rsort($files);
    $lightbox = rand();
    echo '’;

    $skip = $page * $per_page;
    $count = $skip;

    if ( $skip != 0 ) {
    $has_previous = true;
    }
    if ( ! in_array(“thumbs”, $files) ) {
    mkdir(‘thumbs’);
    }

    while ( ($count < $per_page + $skip) && isset($files[$count]) ) {
    $count++;
    if ( !is_dir($files[$count]) && ($type = getPictureType("img/".$files[$count])) != '' ) {
    if ( ! file_exists('thumbs/'.$files[$count]) ) {
    makeThumb($files[$count], $type );
    }
    echo '‘;
    echo ”;
    echo ‘
    ‘;

    }
    }
    echo ”;

    while ( isset($files[$count]) ) {
    if ( !is_dir($files[$count]) && ($type = getPictureType($files[$count])) != ” ) {
    $has_next = true;
    break;
    }
    $count++;
    }
    }
    }

    function getPictureType($file) {
    $split = explode(‘.’, $file);
    $ext = $split[count($split) - 1];
    if ( preg_match(‘/jpg|jpeg/i’, $ext) ) {
    return ‘jpg’;
    } else if ( preg_match(‘/png/i’, $ext) ) {
    return ‘png’;
    } else if ( preg_match(‘/gif/i’, $ext) ) {
    return ‘gif’;
    } else {
    return ”;
    }
    }

    function makeThumb( $file, $type ) {
    global $max_width, $max_height;
    if ( $type == ‘jpg’ ) {
    $src = imagecreatefromjpeg($file);
    } else if ( $type == ‘png’ ) {
    $src = imagecreatefrompng($file);
    } else if ( $type == ‘gif’ ) {
    $src = imagecreatefromgif($file);
    }
    if ( ($oldW = imagesx($src))

    Pictures

    body {
    margin:0 auto;
    }
    #pictures li {
    float:left;
    height:px;
    list-style:none outside;
    width:px;
    text-align:center;
    }
    img {
    border:0;
    outline:none;
    }
    .prev {
    float:left;
    }
    .next {
    float:right;
    }

    <?php
    if ( $has_previous )
    echo '← Previous Page‘;

    if ( $has_next )
    echo ‘Next Page →‘;
    ?>

  19. dvdljns says:

    I am trying to use your script but have one problem. everything works fine untill I click on the thumbnail to see the full size image then it shows up larger then my screen. is there any way to get he script to detect the screen size and give the image that size. If I just go to the folder and click on the image it shows up the right size, so I probally got something wrong. But do not know enough to fix it. can you help me here.

  20. Hyder says:

    Nice article .nowadays there’s another sort of pagination similar to facebook and twitter .
    it’s worth reading , see it guys
    http://youhack.me/2010/05/14/an-alternative-to-pagination-facebook-and-twitter-style/

  21. chip says:

    pagination code for thanx.

  22. tormattis says:

    Hi!
    How can i make this script to display “page-numbers” between “previous” and “next”?
    Like this:

    Previous |3|4|5|6|7| Next

    Thank you for this great script!

    tormattis

  23. Jeff says:

    I’ve tried and got the script working as a standalone. However when I tried to include the script into another file, it “broke”. I’ve tried stripping our everything and moving to the file with include (css, js.ect.)
    Basically the file just has the script, the divs with associated code. it’s then brought into the main file which now has that css and js links. It renders out the html when checked in firebug but the getPictures() , well, isn’t getting, nor is the other references. for the pagination
    I’m by far no programmer and just trod through aimlessly often with PHP so it may be a simple or easy thing that I’m missing.
    Is there solution? need more info?

    Thanks

  24. Anna says:

    This code is great simple to get working but is there a way to paginate this and show the page numbers

  25. Till says:

    Hey Patrick,
    Just wanted to let you know that I’ve been looking for a simple PHP/Lightbox combination photo gallery script for the past 2 days. I finally found your page and this is exactly what I was looking for.
    Thanks for sharing your great work!

  26. Roy says:

    Hi I tested this script and it works great. Although im not sure how to make the directory work. Lets say i wanted to change if ( $handle = opendir(“.”) )
    to if ( $handle = opendir(“../images”) ) this is where my large images are located.
    So would I have to change anyhing els to make that work?

  27. Roy says:

    Also the question tormattis ask about adding pagination numbers.
    If you have a small example please show it. I would love to add a pagination number to this. ;)

  28. greetings says:

    i want a script for load images from folder and with pagination like flicker.. please help me

  29. impe says:

    Nice article!

    What about caching the gallery with pagination?

  1. Create a Simple Picture Gallery using PHP
  2. Web Development Nerdy Daily Links For 3/25/2009 - HUGE POST | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
  3. Защита SimpleTDS от взлома брутфорсом | CetLot

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.