Well, the line you'd want to change is of course the last for statement
for ($i = 1; $i <= $pages; $i++)
$page is the current page I see, and you want that one to be in the middle. Let's say for the sake of argument you want links to the three previous pages and the three following pages.
So the loop should run from $page-3 to $page+3 inclusive.
for ($i = $page-3; $i <= $page+3; $i++)
But if $page is only 2, then there is only one previous page. While if you're on the second-to-last page, there's only one more page following.
So the loop shouldn't start before 1 and should finish after $pages.
So it should start at the greater of 1 and $page-3, and finish at the lesser of $pages and $page+3. The maximum and minumum, in other words.
for ($i = max(1,$page-3); $i <= min($page+3,$pages); $i++)
The efficiency of that can be improved a bit.
$start_counting=max(1,$page-3);
$finish_counting=min($pages,$page+3);
for ($i = $start_counting; $i <= $finish_counting; $i++)
to save recalculating that minimum over and over again.