Reputation: 129
I'm trying to build a webpage that displays images from a folder using PHP. But for some reason it stopped displaying all images within the image folder and only a partial amount. I have pagination within the function, but not all images are being displayed. I checked the directory to ensure the files were in there and they are.
When counting the files I get a total of 76 according to php. The directory has 74 images. But my page is only displaying 60 images. Please help me fix this!
Here's the code I'm working with:
<?php
function show_pagination($current_page, $last_page){
echo '<br><div>';
if( $current_page > 1 ){
echo ' <button class="button" type="button"><a href="?page='.($current_page-1).'"><<Previous</a></button> ';
}
for($i = 1; $i <= $last_page; $i++){
echo ' <button class="button" type="button"><a href="?page='.$i.'">'.$i.'</a></button> ';
}
if( $current_page < $last_page ){
echo ' <button class="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 * ($page - 1)) + 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;
}
echo "Total number of files is $total";
show_pagination($page, $last_page);
for($i = $offset; $i< $max; $i++){
$file = $files[$i];
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo "<a href='$file'><img src='$file' alt='$filename' style='height: 30%; width: 30%; border-style: solid;border-width: 2px;border-color: #000000; margin: 5px'></a>";
}
show_pagination($page, $last_page);
?>
This was working for me at some point and now it doesn't so I'm wondering if there's something inherently wrong with my PHP code. I am new to php.
Upvotes: 0
Views: 60
Reputation: 3997
The issue is with the int
used in your code line:
$last_page = (int)($total / $per_page);
Instead of that use ceil()
as:
$last_page = ceil($total / $per_page);
Reason is that total image 74/20 gives 3.7, if we use int
result will be 3. But its more than that. If we use ceil()
, even 3.1 will be converted as 4. So you will not miss any image.
Upvotes: 1