Get All Photos From Folder and Paginate With PHP

2019-02-11 01:40发布

问题:

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?

回答1:

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 ' <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>';
}

?>