Get All Photos From Folder and Paginate With PHP

后端 未结 1 1321
生来不讨喜
生来不讨喜 2021-01-01 06:52

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 g

相关标签:
1条回答
  • 2021-01-01 07:24

    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>';
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题