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 retrieve these parameters as one big string?

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

test.com/file.php?id=299&mobile=Y&clid=392829

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:

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

id=299&mobile=Y&clid=392829

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.

QUERY_STRING and XSS.

You should never print the QUERY_STRING variable out onto the page without filtering it first. Otherwise, you will leaving yourself open to the possibility of a Cross Site Scripting (XSS) attack:

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 execute on your page.

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

Hopefully, you found this guide useful!

Facebook Comments