Removing URL Parameters From Browser Address Bars
A URL parameter is information appended to a URL. The beginning of parameter information is marked by a "?" character,
As an example, with the https://example.com?name=Will
URL, name=Will
is the parameter information.
When the code in this article is implemented on a page, a browser arriving via a https://example.com?name=Will
link URL will load the page with the https://example.com
URL in the address bar.
Reasons for implementing that include:
-
Removing affiliate codes or other information that might affect sales.
-
Stripping out the information if it should not be included when the page is bookmarked or the link shared.
Whatever the reason might be, this article has a way to do it.
How It Works
When a page begins loading, PHP code checks to see if there are any parameters in the URL.
If yes, PHP reloads the page without the parameters.
If any database updates or cookie setting need to be done based on the parameter information, those should be done before the page is reloaded.
Here is the PHP code. No customization is required. Implementation notes follow the PHP code.
<?php if( isset($_SERVER['QUERY_STRING']) and strlen($_SERVER['QUERY_STRING']) ) { if( headers_sent() ) { echo "<script>location.href='{$_SERVER['PHP_SELF']}'</script>"; } else { header("Location: {$_SERVER['PHP_SELF']}"); } exit; } ?>
The higher in the web page source code that the PHP code is placed, the sooner during the page loading process it will kick in.
But do place the PHP code below any other PHP code that sets cookies or does anything else related to URL parameters. Note that the reload will be without parameters.
If the PHP code is placed below the point where the browser has already sent the header information to the browser, then the PHP code will publish a line of JavaScript to reload the page.
In other words, place the above PHP code as high as is feasible in the web page source code so long as it is below other PHP code that expects URL parameter information. If the placement is too low to use the PHP header() function, JavaScript will be published to affect the reload.
Like any other coding, test it before going live.
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager