PHP: Get the full query string.

This is a tutorial on how to get the FULL query string as a string using PHP.

Most people are aware of how to retrieve URL parameters using the $_GET array. However, what if you wanted to retrieve these parameters as a string?

Let’s say, for example, that we have the following URL:

As you can see, the query string in the URL above contains three GET parameters.

If we want to retrieve everything after the question mark and assign it to a string, we can simply access the QUERY_STRING element in the $_SERVER superglobal array like so:

//Get the full string
$queryString = $_SERVER['QUERY_STRING'];

If we were to run our code snippet above on the URL in question, it would return the following string:


Note how this string does not contain the question mark symbol. If this symbol is needed, then you will need to re-add it yourself.

What if there is no query string?

If there is no query string, then the QUERY_STRING key in $_SERVER will be an empty string.

Unlike other elements in the $_SERVER array, QUERY_STRING should always exist.

Why is this useful?

This can be useful for a number of reasons.

The first two that spring to mind are:

  1. You can use the string to build pagination links.
  2. It can be used to get the full URL of a web page.


You should never print the QUERY_STRING variable out onto the page without filtering it first.

If you do this, you will leave yourself open to the possibility of a Cross Site Scripting (XSS) attack.

$queryString = $_SERVER['QUERY_STRING'];
echo '<a href="file.php?' . $queryString . '">Link</a>';

The code above is vulnerable to XSS because the QUERY_STRING result is being printed out without any sort of filtering. As a result, malicious users could potentially put JavaScript code into the query string and have it executed on your page.

To be safe, you should wrap it in the htmlentities function like so:

//Example using htmlentities
$queryString = $_SERVER['QUERY_STRING'];
echo '<a href="file.php?' . htmlentities($queryString) . '">Link</a>';

Hopefully, you found this guide useful!