1

I had done this using my MySQL db, but about a year ago, I revamped my site to a more conveniently-coding layout for my photography thumbnails. Someone else had written the code, and it uses the opendir functionality to auto-create thumbnail images based on the image files in a particular folder.

The problem is if I have a gallery with 100+ images in it, it loads all of them on the page and the user can't select anything to view until they've all loaded.

I want to create pagination to load, say, 15 at a time and then allow the user to go to the other pages (if there are any). This code was written way over my head, as I'm quite the PHP novice.

Here is the code I think is relevant that needs to be updated:

$dir = $dir.$gallery."/";

//Put files into an array
// create a handler to the directory
$dirhandler = opendir($dir);

// read all the files from directory

$nofiles=0;
while ($file = readdir($dirhandler)) {

// if $file isn't this directory or its parent 
//add to the $files array
if ($file != '.' && $file != '..')
{
$nofiles++;
$files[$nofiles]=$file;                
}   
}

//close the handler
closedir($dirhandler);

// sort folder names alphabetically, ignore case
natcasesort($files); 
?>

<div style="clear:both"></div>

<?
//Show images
foreach ($files as $file){   
if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{       
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group' href='$dir$file' return='false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'>";
echo"</a><br>";
echo "</div>";
}
}
}   
?>

That might not even be everything. Honestly, I'm willing to pay someone to do this for me. I don't know how hard or easy it is. I can send the entire page or copy the entire code if necessary.

I spent 7 hours yesterday trying to convert my site into a WordPress layout where there is a web gallery plugin that already does this, but the mobile layout is a mess and it's a little more complicated than what this code already does easily.
I think my current site looks and works great, but this pagination is the only thing missing.

David Ansermot
  • 6,052
  • 8
  • 47
  • 82
sleepywan
  • 27
  • 1
  • 5

2 Answers2

0

You seem to have the bulk of the work done already and you have stored references to the files in an array so you should be able to use the slice method to retrieve portions of the array as you wish. Pseudo code to give you the idea:

$total_to_display=10;
$pn=$_GET['pn'];
$preserve=true;

$slice=array_slice( $files, $pn, $total_to_display, $preserve );

foreach( $slice as $key => $file ) echo "<img src='$file' />";

Following on from the above, here is a tested version which works - though there may well be things that need attention as it has not been rigorously tested!

        define('ROOT','c:/wwwroot' );
        $dir='/images/gallery/loch_clunie_April07';
        $fullpath=realpath( ROOT . $dir );
        $files=array();

        if( $fullpath ){
            /* Find jpg, png and gif images in nominate directory */
            $filepaths=preg_grep( '@\.jpg|\.png|\.gif@i', glob( $fullpath . '/*' ) );

            /* Prepare an array to hold data about each image in directory */
            foreach( $filepaths as $path ){
                $info=(object)pathinfo( $path );
                list( $width, $height, $type, $attr ) = getimagesize( $path );
                $files[]=array( 'name'=>$info->basename, 'dir'=>$dir, 'ext'=>$info->extension, 'size'=>filesize( $path ), 'created'=>filectime( $path ), 'width'=>$width, 'height'=>$height );
            }


            /* Set default values to prevent errors */
            $tR=0;
            $mR=0;
            $tP=0;
            $pN=0;

            /* Number of images to display */
            $mR=15;
            /* Total number of images found in directory */
            $tR=count( $files );
            /* Current page number */
            $pN=isset( $_GET['pN'] ) ? filter_var( filter_input( INPUT_GET, 'pN', FILTER_SANITIZE_NUMBER_INT ), FILTER_VALIDATE_INT ) : 0;
            /* Determine number of pages */
            $tP=( $mR > 0 ) ? abs( ceil( $tR / $mR ) - 1 ) : 0;


            /* Ensure that the page number is valid based upon number of records to display AND number of images found */
            if( abs( $mR * $pN ) > $tR-1 ) $pN=0;




            $slice=array_slice( $files, abs( $pN * $mR ), $mR, false );
            foreach( $slice as $key => $array ){
                $img=(object)$array;
                echo "
                <div class='imgwrapper'>
                    <a class='fancybox' rel='group' href='{$img->dir}{$img->name}' return='false' title='{$img->name}'>";
                    /* Replace the following with your timthumb code */
                echo "
                        <img src='{$img->dir}/{$img->name}' />";
                /*
                echo "
                        <img src='timthumb.php?src={$img->dir}{img->name}&h={$img->height}&w={$img->width}' alt='{$img->ext}' width='{$img->width}' height='{$img->height}'>";
                */
                echo "
                    </a>
                </div>";
            }





            /* Display pagination links - You might wish to prefix the actual links with the path to the gallery page rather than just ?pN=X etc */
            if( $tP > 0 && $tR > $mR ){
                echo "<div class='rspaging'>";

                if( $pN==0 ) echo "<div id='paging_first'>First</div>";
                else echo "<a href='?pN=0'>First</a>";

                if( $pN > 0 ) echo "<a href='?pN=".max( 0, $pN - 1 )."'>Previous</a>";
                else echo "<div id='paging_previous'>Previous</div>";

                if( ( $pN + 1 ) > $tP ) echo "<div id='paging_next'>Next</div>";
                else echo "<a href='?pN=".min( $tP, $pN + 1 )."'>Next</a>";

                if( $pN==$tP ) echo "<div id='paging_last'>Last</div>";
                else echo "<a href='?pN={$tP}'>Last</a>";

                echo "</div>";
            }
        }
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Thank you for the reply. Unfortunately, like my response above, I have no idea where to put this or what it does. I was serious about paying someone to do this. I'm just not familiar enough with the method of retrieving the images the way this code does, – sleepywan Apr 27 '15 at 03:40
0

Ok so, you'll need to count the number of files you have

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
//if doesnt work replace __DIR__ with the path to your gallery
$amountfile = (int) iterator_count($fi);
// $amountfile is the number of file you got in one directory
$amountpage = (int) $amountfile / 15 
// this number will tell us how much page with 15 pictures you gonna have

At the end of the page we need to create à little form in order to get to other pages

<form action="THISFILE.php" method="GET">

<?php

for($i=0; $i<= $amountfile, $i++){

   echo "<input type="submit" name='page' value=";
   echo $i;   
   echo "'>";

}   

?>

</form>

This will reload the file and by GET the number of the page. Next you have to intercept the GET with the following code

if($_GET['page'])
{
   $choice = (int) $_GET['page'];
   $page = ($choice -1) * 15;
}
else
{
   // in case we have not clicked on a specific page there is no GET    
   $page = 0;
}

then we just have to modify your loop so that it'll show only the 15 pictures depending on your page choice. So imagine you click on page " 2 " it will do -> (2-1) * 15
So your $page will be 15 and so only begin to show picture once we have been through de loop 15 times it will stop 15 loops further.

In the following loop that you gave us i put in an other little if, if you look at the end of your loop you'll see $number++. That increments $number by one each time it runs the loop. It will show only the image between 15 and 15+15 (30)

$number = 0;
foreach ($files as $file){   
if($number > $page  && $number < $page + 15){


if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{       
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group' href='$dir$file' return='false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'>";
echo"</a><br>";
echo "</div>";
}
elseif($number > $page + 15)
{
// this stop the loop while you have showed your 15 pictures
break;
}


$number++
}
}
} 

I didn't try it out, but i hope you get the general idea.

Bidoubiwa
  • 910
  • 2
  • 12
  • 25
  • You clearly put in a lot of effort, and I appreciate that. unfortunately, it's all lost on me. :( I have no idea where that goes and what it interacts with (since there's obviously more code on the page I have that I didn't include). From the way I did the code on my previous page (MySQL), it was much simpler, so I guess I thought it would be a smaller snippet. – sleepywan Apr 27 '15 at 03:38
  • well, if you want we can go on skype, but i have no idea how to pm you. The thing is you dont go by your database to get information, so you can't use LIMIT. The information you retrieve is from your folders, not your database. – Bidoubiwa Apr 27 '15 at 16:22
  • No worries - I appreciate your help. I was hoping it would be a simpler task than it appears to be, so I'll have to figure something else out. Thanks for taking the time to reply and assist. – sleepywan Apr 28 '15 at 03:31