In other words, the bounds on your loop are dependent on the current page, not just 1..$numpages?
You don't say which page has links 1..5 at the bottom and which has links 2..6; I'll assume that you show links 1..5 on page 3, links 2..6 on page 4, etc., and that the current page is in $page (as it would be, from the previous page).
This goes in just before the loop:
$firstpage=max(1,$page-2);
$lastpage=min($numpages,$firstpage+4);
//max and min are to prevent falling off either end.
// Increase the 2 to allow links to reach further back in the list of pages;
// Increase the 4 to provide more pages
Then the loop starts:
for($i=$firstpage; $i<=$lastpage; ++$i)
{....and we proceed as before
If you're on $page=3, then $firstpage has the value $page-2=1, and $lastpage has the value $firstpage+4=5, so $i runs from 1 to 5.
If you're on $page=42, and there are only 43 pages in the whole document, then $firstpage has the value $page-2=40 and $lastpage has the value 43 (because 43 is less than $40+4).