Get All Photos From Folder and Paginate With PHP - php

I'm trying to build a site that has a photo gallery and rather than build a database CMS I'm trying it with the use of PHP and folders. At the moment I have a script to get all of the images in a folder and display them on a page, however as there are going to be probably in excess of 100 photo's I'd like to use pagination to spllit this over several pages but I have no idea how to do this.
Here is the script I'm currently running:
<?php
$folder = 'cms/gallery/photo/';
$filetype = '*.*';
$filename = HOW DO I GET THE NAME WITHOUT FILE TYPE
$files = glob($folder.$filetype);
foreach ($files as $file)
{
echo '
<div class="galleryCellHolder">
<div class="galleryCell">
<a class="fancybox" rel="group" href="'.$file.'"><img class="galleryPhoto" src="'.$file.'" alt="'.$filename.'"></a>
</div>
</div>
';
}
?>
Q1 - How do I extract the file name without the file extension?
Q2 - How do I paginate this for say 24 images per page?

For paging you must calculate the total items to page , capture the parameter of the current page and iterate over the respective range.
<?php
$folder = 'cms/gallery/photo/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$total = count($files);
$per_page = 6;
$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;
}
You can use the function pathinfo to get the file name without extension.
//print_r($files);
echo "Processsing page : $page offset: $offset max: $max total: $total last_page: $last_page";
show_pagination($page, $last_page);
for($i = $offset; $i< $max; $i++){
$file = $files[$i];
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo '
<div class="galleryCellHolder">
<div class="galleryCell">
<a class="fancybox" rel="group" href="'.$file.'"><img class="galleryPhoto" src="'.$file.'" alt="'.$filename.'"></a>
</div>
</div>
';
}
show_pagination($page, $last_page);
Using the following function you can create the navigation links
function show_pagination($current_page, $last_page){
echo '<div>';
if( $current_page > 1 ){
echo ' <<Previous ';
}
if( $current_page < $last_page ){
echo ' Next>> ';
}
echo '</div>';
}
?>

Related

PHP pagination function generates more pages than needed [the last page is empty] sometimes. How do I fix this?

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">First Page</button> ';
echo ' <button type="button">Last Page</button> ';
if( $current_page > 1 ){
echo ' <button type="button"><<Previous</button> ';
}
for($i = 1; $i <= $last_page; $i++){
echo ' <button type="button">'.$i.'</button> ';
}
if( $current_page < $last_page ){
echo ' <button type="button">Next>&gt</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.
I' m fairly certain the problem lies in your offset - $offset = ($per_page + 1)*($page - 1).
Keep in mind that each page will show twenty items, not twenty one. For the first page, you want an index of 1. For the second, 21. For the third, 41. And so on.
As such, you'll only want to add the one after the page itself has been calculated. For this, you're probably looking for the following:
$offset = ($per_page * ($page - 1)) + 1;
Which equates to:
$offset = (20 * (1 - 1)) + 1; /* 1 for page 1 */
$offset = (20 * (2 - 1)) + 1; /* 21 for page 2 */
$offset = (20 * (3 - 1)) + 1; /* 41 for page 3 */

Get File Name With PHP

I'm using a php script to get all of the images from a folder and paginate them and everything works fine, however I'd like to use the actual photo name (filemname) as the alt tag but I'm finding it difficult to get the name. Any way that this can be done with the following code:
<?php
//The directory to your images folder, with trailing slash
$dir = "cms/gallery/photo/";
//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg,gif,png";
//Set the number of images you want to display per page
$imagesPerPage = 3;
//Set the $page variable
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);
//Count the number of images
$totalImages = count($images);
//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);
//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
//Set the currnet page to the total pages.
$page = $totalPages;
}
//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;
//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
//We need to make sure that its within the range of totalImages.
if($i < $totalImages){
//Now we can display the image!
echo "
<div class='galleryCellHolder'>
<div class='galleryCell'>
<a class='fancybox' rel='group' href='{$images[$i]}'><img class='galleryPhoto' src='{$images[$i]}' alt='I NEED THIS TO BE THE FILE NAME'></a>
</div>
</div>
";
}
}
//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
if($p == $page){
$tmp_pages[] = "<strong class='pagination'>{$p}</strong>";
}else{
$tmp_pages[] = "<a class='pagination' href='?page={$p}'>{$p}</a>";
}
}
?>
use basename().
$filename = explode('.', basename($images[$i]));
echo "
<div class='galleryCellHolder'>
<div class='galleryCell'>
<a class='fancybox' rel='group' href='{$images[$i]}'><img class='galleryPhoto' src='{$images[$i]}' alt='" . $filename[0] . "'></a>
</div>
</div>
";
Do it inside Your loop:
var_dump(basename($totalImages[$i]));
Or You can also check:
var_dump(pathinfo($totalImages[$i]));
There will be also basename, with dirname, extension etc.

Adding filename to glob script

I am using the following script to display all my images on a page. I am looking to have about 12000 images in this folder, hence the need for pagination. The files names are numbers in ascending order 1 - 12000 and must be displayed in order.
<?php
$dir = "../image/thumb/";
//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg";
//Set the number of images you want to display per page
$imagesPerPage = 20;
//Set the $page variable
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);
//Count the number of images
$totalImages = count($images);
//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);
//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
//Set the currnet page to the total pages.
$page = $totalPages;
}
//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;
//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
//We need to make sure that its within the range of totalImages.
if($i < $totalImages){
//Now we can display the image!
echo "<img src='{$images[$i]}' alt='{$images[$i]}' />";
}
}
//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
if($p == $page){
$tmp_pages[] = "<strong>{$p}</strong>";
}else{
$tmp_pages[] = "<a href='?page={$p}'>{$p}</a>";
}
}
//Now display pages, seperated by a hyphon.
echo "<br />" . implode(" - ", $tmp_pages);
?>
I need to have the filenames echo below each image how can I achieve this?
Many thanks in advance.
===== EDIT =====
This script now works with thanks to SuperScript The complete code is:
<?php
//The directory to your images folder, with trailing slash
$dir = "../image/thumb/";
//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg";
//Set the number of images you want to display per page
$imagesPerPage = 20;
//Set the $page variable
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);
usort($images,function($a,$b){
$a=(int)preg_replace('~\D~','',$a);
$b=(int)preg_replace('~\D~','',$b);
return $a<$b?-1:1;
});
//Count the number of images
$totalImages = count($images);
//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);
//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
//Set the currnet page to the total pages.
$page = $totalPages;
}
//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;
//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
//We need to make sure that its within the range of totalImages.
if($i < $totalImages){
//Now we can display the image!
// echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><a class=\"filename\">" . basename($images[i]) . "</a>";
echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><p>" . basename($images[$i]) . " </p>";
}
}
//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
if($p == $page){
$tmp_pages[] = "<strong>{$p}</strong>";
}else{
$tmp_pages[] = "<a href='?page={$p}'>{$p}</a>";
}
}
//Now display pages, seperated by a hyphon.
echo "<br />" . implode(" - ", $tmp_pages);
?>
Try changing your echo line (//Now we can display the image!):
echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><p>" . basename($images[$i]) . "</p>";
The basename() function returns just the filename of a file.
And to sort correctly, add this line after you get $images:
usort($images,function($a,$b){
$a=(int)preg_replace('~\D~','',$a);
$b=(int)preg_replace('~\D~','',$b);
return $a<$b?-1:1;
});

Display images with pagination from mysql

I had a php page to display images from a mysql database. It displays all the images uploaded in 1 page one after the other. How can i display 5 or 6 images per page with pagination?
Here is my php page.
<?Php
include("init.php");
include("template/header.php");
?>
<div class="view_albums"><h3> View Albums </h3>;
<?php
$album_id = $_GET['album_id'];
$images = get_images($album_id);
if (empty($images)) {
echo 'There are no images ';
} else {
foreach ($images as $image) {
?> <div class="box"> <?php
echo ' <img class="box1" src="uploads/thumbs/', $image['album'], '/', $image['id'], '.', $image['ext'], '" title="Uploaded on ', date('l F j, Y \a\t g:i A',$image['timestamp']),'"> [delete]';
?> <?php
}
}
?>
</div>
</div>
<?php
include("template/footer.php");
?>
try to use the below pagination function
function genPagination($total,$currentPage,$baseLink,$nextPrev=true,$limit=10)
{
if(!$total OR !$currentPage OR !$baseLink)
{
return false;
}
//Total Number of pages
$totalPages = ceil($total/$limit);
//Text to use after number of pages
$txtPagesAfter = ($totalPages==1)? " page": " pages";
//Start off the list.
$txtPageList = '<br />'.$totalPages.$txtPagesAfter.' : <br />';
//Show only 3 pages before current page(so that we don't have too many pages)
$min = ($page - 3 < $totalPages && $currentPage-3 > 0) ? $currentPage-3 : 1;
//Show only 3 pages after current page(so that we don't have too many pages)
$max = ($page + 3 > $totalPages) ? $totalPages : $currentPage+3;
//Variable for the actual page links
$pageLinks = "";
//Loop to generate the page links
for($i=$min;$i<=$max;$i++)
{
if($currentPage==$i)
{
//Current Page
$pageLinks .= '<b class="selected">'.$i.'</b>';
}
else
{
$pageLinks .= ''.$i.'';
}
}
if($nextPrev)
{
//Next and previous links
$next = ($currentPage + 1 > $totalPages) ? false : 'Next';
$prev = ($currentPage - 1 <= 0 ) ? false : 'Previous';
}
return $txtPageList.$prev.$pageLinks.$next;
}
think it will help you

Adding description tag to PHP image gallery

I am trying add a descriptive tag under each image but most of the code is in PHP and i am not to familiar with how to program it without screwing up the whole structure. Here is the website: http://suncoastdeck.com/index.php?page=portfolio&start=0
Here is the code for the portfolio page:
<div class="content-box">
<?
//total number of images
$total = 77;
//max number of thumbnails per page
$max = 9;
//what image do we want to start from?
$startcount = $_GET["start"];
//if there is not a defined starting image, we start with the first
if(empty($startcount))
{
$startcount = 0;
}
//start off the loop at 1
$loop = 1;
//start the loop
while($loop <= $max)
{
//for the picture labels
$num = $startcount + $loop;
if($num > $total)
{
$num = $num - 1;
break;
}
// Add class="last" to every third list item
if(is_int($num / 3))
{
$last = ' class="last"';
}
else
{
$last = "";
}
//the code for the image
echo '
<li'.$last.'><img src="images/portfolio/thumbs/pic-'.$num.'-thumb.jpg" width="256" height="138" alt="Thumbnail of image '.$num.'" /><div>'.$num.'</div></li>';
//add 1 to the loop
$loop++;
}
echo '</ul>';
//Calculate the number of pages
$total_pages = $total / $max;
//clean it up
if(!is_int($total_pages))
{
$total_pages = floor($total_pages) + 1;
}
//start the page count at 1
$ploop = 1;
echo '<hr /><div id="portfolio-wrap"><div id="pages">Page: ';
while($ploop <= $total_pages)
{
$offset = ($ploop * $max) - $max;
if($startcount == $offset)
{
echo '<span>'.$ploop.'</span>';
}
else
{
echo ''.$ploop.'';
}
$ploop++;
}
echo '</div>';
echo '<div id="portfolio-foot-left"><p>Displaying Images <strong>'.($startcount + 1).' - '.$num.'</strong> of <strong>'.$total.'</strong></p></div></div>';
?>
Pretty much what i want is to make section drop down a bit more where i can add in additional info about the pic. Any suggestions?
You need a database or else you can store your descriptions in a text file next to the image. What have you tried so far?
Basically you need to create a form that accepts the image name and caption, take the caption and write it to a file or database. Then when displaying the caption, you just add a <div> that reads from file with file_get_contents(). Why don't you copy the script to another directory and start experimenting? People probably won't write the whole thing for you ;)

Categories