By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

How to disallow URL parameters in PHP

Disallow or Remove the URL parameters that are not used by your scripts, and avoid having to deal with duplicate content the incorrect way.

Edited: 2015-06-12 20:33

You may have noticed how some websites correctly throws a 404 error if you type in unused URL parameters in the URL. This can be done by checking the REQUEST_URI server variable for URL parameters. Its a very good idea to do this, since users may otherwise start linking to non-existing URLs, and this could then lead to duplicate content issues, or problems with your sites indexing.

What we do in this simple script, is simply to check for the existence of the question mark in the requested URL, this would still allow you to use search engine friendly URLs, and block access to all URL Parameters.

if (preg_match("/\?/", $_SERVER['REQUEST_URI'])) {
  header('HTTP/1.1 404 Not Found');
  include '404.php';

Allow chosen URL parameters

You can also chose to allow just some select URL parameters, this is useful if you have admin scripts and such, which uses them to handle content. To do this its easier to use the QUERY_STRING server variable, as it will simply take the part after the question mark, this part is called the quary string and contains all the url parameters.

if (!preg_match("/PostID|ForumPostID|DeletePost/", $_SERVER['QUERY_STRING'])) {
 echo 'No Known Parameter Found!';
echo 'Valid Parameter Found!';

As you can see, it becomes harder when you want to allow for multiple parameters to be present at the same time, in which case you would want to do multiple checks. First check if a single parameter was present, then check if your allowed combination was used. Otherwise, if you just do like above, any combination of at least one used parameter, and at least one unused would return true.

if (preg_match("/(^PostID=[^\&]+$)|(^ForumPostID=[^\&]+$)|(^DeletePost=[^\&]+$)/", $_SERVER['QUERY_STRING'])) {
 // Allows all these parameters, but no combination usage.
 echo 'Valid Parameter Found! ' .$_SERVER['QUERY_STRING'];
} else if (preg_match("/^PostID=[0-9]+\&ForumPostID=[0-9]+$/", $_SERVER['QUERY_STRING'])) {
 // Allows a combination to be used.
 // Add more checks if you want more combinations!
 echo 'Valid Parameter combination Found! ' .$_SERVER['QUERY_STRING'];
echo 'No valid Parameter Found! ' .$_SERVER['QUERY_STRING'];