Reputation: 613
I'm developing a search function for a web, until now works like a charm but i have an issue with the pagination. I have the following URL format:
https://www.server.com/search?w=something&re=34&page=1
I need to change specifically the page number in the URL, i have a function that retrieves the full URL but is not useful because when i click on the page number it does this:
https://www.server.com/search?w=something&re=34&page=1&page=2&page=3
I need to replace specifically the page= to the number i want. How can i achieve this?
The full code of the function is this:
function PAGINAR($page,$totalPages){
global $link;
$nextpage= $page + 1;
$prevpage= $page - 1;
$paginado = '<ul id="pagination-digg">';
if ($page == 1){
$paginado .= '<li class="previous-off">« Previous</li>';
}else{
$paginado .= '<li class="previous"><a href="'.getUrl().'&page='.$prevpage.'">« Previous</a></li>';
}
for($i = max(1, $page - 5); $i <= min($page + 5, $totalPages); $i++){
if ($page == $i){
$paginado .= '<li class="active">'.$i.'</li>';
}else{
$paginado .= '<li><a href="'.getUrl().'&page='.$i.'">'.$i.'</a></li>';
}
}
if($totalPages > $page ){
$paginado .= '<li class="next"><a href="'.getUrl().'&page='.$nextpage.'">Next »</a></li>';
}else{
$paginado .= '<li class="next-off">Next »</li>';
}
$paginado .= '</ul>';
return $paginado;
}
And this retrieves the URL
function getUrl() {
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
Thanks in advance
Upvotes: 0
Views: 74
Reputation: 12689
Here is one example that might help you:
$url = 'https://www.server.com/search?w=something&re=34&page=1';
parse_str( parse_url( $url, PHP_URL_QUERY ), $params );
$params['page'] = 2;
echo http_build_query( $params ); // outputs: w=something&re=34&page=2
parse_url
parse_str
http_build_query
Upvotes: 1
Reputation: 1823
This is a great example of why you don't want your back-end dictating your front-end. Ideally you should be passing back only the result set with the current page number and letting the front-end generate the first and last page links.
But since you're doing it this way, the problem is REQUEST_URI already contains the variable page. So you have two options:
1. Parse REQUEST_URI to either get the page parameter out or replace the number of the page with the number you want
preg_replace('/page=\d+/', 'page=' . $nextPage, $_SERVER['REQUEST_URI'])
2. Parse out the script variables (everything after '?') and re-attach the vars you want from $_GET
$baseUrl = explode('?', $_SERVER['REQUEST_URI'])[0];
$varArray = $_GET;
unset($varArray['page']);
$url = $baseUrl . '?' . implode('&', $varArray);
If this seems hacky, its because it is. Use JSON and let the front-end deal with setting up the front-end.
Upvotes: 1