Simple PHP pagination

This post is mostly for myself 🙂 I want to have a place I can reach when implementing another pagination in PHP. The one presented below is rather simple. It is always showing all pages links, there is no fancy logic to hide some of them if there are too many.

Please note that this pagination assumes that your data structure always contains all records. There is no database query to limit them. If your data contains a lot of records, this solution is not optimal.

How does it work?

In a few words – first we have to set some variables: initial page number (defaulted to 1), number of items (posts) per page, maximum page number. I don’t want user to enter bogus page number and blow things away.

Next, I check what is the page number sent in URL of the document. In my code, the “get” variable is handled by an additional function for safety reasons. If you are using PHP framework, check what is the proper way to handle URL variables. Once I have the page number, I check if it fits in the limits – between the maximum page number and one.

With the proper page number, we can calculate the first and last posts that should be displayed. Having all the above, we can finally generate the pagination contents – links to the pages.

As the last step we are displaying all posts that fit in the selected page. Below posts there are pagination links displayed.

The code

Below you can review the whole code of the pagination.

<?php
    $page = 1;
    $posts_per_page = 10;
    $max_page = ceil(count($posts) / $posts_per_page);

    // page number defined in URL (adjust below as per your needs)
    $get_page = get_variable_from_URL('page');    

    // make sure that the page number fits in range
    if (($get_page) && (is_numeric($get_page))) {
        $page = max(min(ceil($get_page), $max_page), 1);
    }

    // calculate first and last post
    $start_post = (($page - 1) * $posts_per_page);
    $end_post = min(($page * $posts_per_page), count($posts));

    // generate pagination links
    $pagination = "";
    if ($max_page > 1) {
        $pagination .= "<div class=\"pagination\">";
        for ($i=1; $i<=$max_page; $i++) {
            $pagination .= "<a href=\"" . $page_url . "?page=" . $i . "\" " 
                . (($i==$page)?"class=\"active\"":"") . " >" . $i . "</a>";
        }
        $pagination .= "</div>";
    }
?>

<?php for ($i=$start_post; $i<$end_post; $i++): ?>
    <?php $post = $posts[$i] ?>
    <div class="blog-body">
        <?php echo $post['contents'] ?>
    </div>
<?php 
    endfor;
    echo $pagination;
?>