Get all photos from folder and pagination using PHP

I am trying to create a photo gallery site and not create a CMS database. I am trying to use it using PHP and folders. At the moment I have a script to get all the images in a folder and display them on the page, however there will probably be over 100 photos. I would like to use pagination to split this into multiple pages, but I have no idea how.

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 to extract filename without file extension? Q2 - How do I do this to display 24 images per page?

+3


source to share


1 answer


For paging, you have to compute the common elements on the page, grab the parameter of the current page, and iterate over the appropriate 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 pathinfo function to get the filename without the 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 navigation links

function show_pagination($current_page, $last_page){
    echo '<div>';
    if( $current_page > 1 ){
        echo ' <a href="?page='.($current_page-1).'"> &lt;&lt;Previous </a> ';
    }
    if( $current_page < $last_page ){
        echo ' <a href="?page='.($current_page+1).'"> Next&gt;&gt; </a> ';  
    }
    echo '</div>';
}

?>

      

+7


source







All Articles