I am trying to add a pagination to my image gallery that I’ve made entirely in PHP.
I used this post for it as it was the best fit I found.
However, browsing around I noticed that it’s not working overall.
For example, I have a folder with 206 files and within 11 pages (18 per page) only shows 196 images.
I have another with 35 files and it doesn’t go past the first page and so 18 images.
This is the code, where am I going wrong?
Please speak like I’m stupid because all of this I have done it’s been out of my brain with no previous study or knowledge of PHP. Thanks
<div>
<?php
$folder = './././';
$filetype = '*.jpg*';
$files = glob($folder.$filetype);
$total = count($files);
$per_page = 18;
$last_page = (int)($total / $per_page);
if(isset($_GET["page"]) && ($_GET["page"] <=$last_page) && ($_GET["page"] > 0) ){
$page = $_GET["page"];
$offset = ($per_page + 1)*($page - 1);
}else{
$page=1;
$offset=0;
}
$max = $offset + $per_page;
if($max>$total){
$max = $total;
}
for ($i = $offset; $i< $max; $i++) {
$image = $files[$i];
$info = pathinfo($image);
$resolution = getimagesize($image);
$file = $files[$i];
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo '<div class="thumbs">';
echo '<a target="_blank" href="'.$file.'"><img src="'.$image.'"></a><br>';
echo '<span class="thumb_size">' . strval($resolution[0]) . 'x' . strval($resolution[1]) . '</span>';
echo '</div>';
}
show_pagination($page, $last_page);
?>
</div>
<?php function show_pagination($current_page, $last_page){
echo '<div class="pagination">';
if( $current_page > 1 ){
echo '<span class="button-14"><a href="?page='.($current_page-1).'"> <<Previous Page</a></span> ';
}
if( $current_page < $last_page ){
echo '<span class="button-14"><a href="?page='.($current_page+1).'"> Next Page>></a></span>';
}
echo '</div>';
}?>
2
Answers
Two changes necessary for this coding to work.
$last_page = (int)($total / $per_page);
into$last_page = ceil($total / $per_page);
to allow me showing the pagination button even for one image remaining.
$offset = ($per_page + 1)*($page - 1);
into$offset = ($per_page)*($page - 1);
not to have one image get lost in between switching pages and show them all.
Full credits to David for helping in this.
The
$last_page
is off by 1. Consider what you’re doing here:If there’s any remainder from that calculation, casting to
int
will drop that remainder. So the last incomplete page of records is never available.Instead of casting to an
int
, use theceil()
function:That way if there’s any remainder, even just a single extra record, the
$last_page
will always round up to account for that remainder.