Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with $_SERVER['QUERY_STRING']

Tags:

php

How to work with $_SERVER['QUERY_STRING'] and pagination?

When my table is sorted by this link:

<a href="'.$_SERVER['PHP_SELF'].'?sort_name=name&sort=asc" title="'.$lang['sorteer_asc'].'"></a>

My url becomes: relation.php?sort_name=adres&sort=asc

The I use an pagination link:

echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&page='.$i.'">'.$i.'</a> '; 

And the url becomes: relation.php?sort_name=adres&sort=asc&page=2

So far so good but when browsing to other pages it can be as long as: relation.php?sort_name=adres&sort=asc&page=2&page=3&page=14&page=23&page=27

The age keeps appearing because of the $_SERVER['QUERY_STRING'], how can I clean up my url with only keeping the last page and ?sort_name=adres&sort=asc.

Or do you suggest an other solution of ordering and pagination?

like image 211
Muiter Avatar asked Jan 31 '11 21:01

Muiter


People also ask

What is $_ SERVER Query_string?

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string. $_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request. $_SERVER['HTTP_ACCEPT_CHARSET']

What is $_ SERVER [' Request_uri '] in PHP?

$_SERVER['REQUEST_URI'] contains the URI of the current page. So if the full path of a page is https://www.w3resource.com/html/html-tutorials.php, $_SERVER['REQUEST_URI'] would contain /html/html-tutorials. php.

What is $_ SERVER [' Script_name ']?

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.

What is $_ SERVER [' PHP_SELF ']?

$_SERVER['PHP_SELF'] Contains the file name of the currently running script. $_SERVER['GATEWAY_INTERFACE'] Contains the version of the Common Gateway Interface being used by the server.


1 Answers

Instead of reusing QUERY_STRING, you should assemble it anew with http_build_query().

// Merge $_GET with new parameter
$QS = http_build_query(array_merge($_GET, array("page"=>2)));

// You should apply htmlspecialchars() on the path prior outputting:
echo "<a href='" . htmlspecialchars("$_SERVER[PHP_SELF]?$QS") . "'> $i </a>";

Thus you have all current $_GET parameters included, but can add or replace entries with new values. And it's ensured that each appears only once.

like image 93
mario Avatar answered Sep 22 '22 05:09

mario