分页与php限制来自get变量的链接数

I am making a simple image gallery and have hit a road block. Its simply displaying a number of images and using pagination to separate 16 images per page. This all works as does my current pagination. However my pagination bar has 101 buttons on it. I want to limit that to a range of 8 pages 4 on either side of the current page and 8 on either side if at beginning or end etc. My current_page and last_page variables are simply a get variable from the page address. Is there a simple way to accomplish this.

for ($i = 1; $i < ($last_page + 1); $i++) {
    if ($current_page == $i) {
        echo '<li class="active"><a href="?page=' . $i . '">' . $i . '</a></li>';
    } else {
        echo '<li><a href="?page=' . $i . '">' . $i . '</a></li>';
    }
}
$currentPage = 4;
$numberPages = 8;
$maxPages = 106;
for ($i = $currentPage - ((int)($numberPages/2)), $pages = 0; $pages < $numberPages && $i <= $maxPages; $i++) {
    if ($i > 0) {
        if ($i == $currentPage) {
            echo '<li class="active"><a href="?page='.$i.
            '">'.$i.
            '</a></li>';
        } else {
            echo '<li><a href="?page='.$i.
            '">'.$i.
            '</a></li>';
        }
        $pages++;
    }
}

Something along these lines should work