I just found a pagination function to display pages of images from a folder, however when paginating it the last few pages seem to be empty and I don't want this. Here's the code I'm working with:
<?php
function show_pagination($current_page, $last_page){
echo '<br><div>';
echo ' <button type="button"><a href="?page=1">First Page</a></button> ';
echo ' <button type="button"><a href="?page='.$last_page.'">Last Page</a></button> ';
if( $current_page > 1 ){
echo ' <button type="button"><a href="?page='.($current_page-1).'"><<Previous</a></button> ';
}
for($i = 1; $i <= $last_page; $i++){
echo ' <button type="button"><a href="?page='.$i.'">'.$i.'</a></button> ';
}
if( $current_page < $last_page ){
echo ' <button type="button"><a href="?page='.($current_page+1).'">Next>></a></button> ';
}
echo '</div><br>';
echo '<div><p>Page '.$current_page.' out of '.$last_page.'</p></div><br>';
}
$folder = 'images/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$total = count($files);
$per_page = 20;
$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{
//echo "Page out of range showing results for page one";
$page=1;
$offset=0;
}
$max = $offset + $per_page;
if($max>$total){
$max = $total;
}
show_pagination($page, $last_page);
for($i = $offset; $i< $max; $i++){
$file = $files[$i];
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo "<img src='$file' alt='$filename' style='border-style: solid;border-width: 2px;border-color: #4d94ff; margin: 5px'>";
}
show_pagination($page, $last_page);
?>
Any help resolving this minor issue will be greatly appreciated. However I'm calculating the last page seems to work in some cases, but doesn't work in all cases, I'm not sure why.