$_GET data is usually passed to the browser to indicate what page or article to load from a Website and may be used to make a query to your MySQL database. You probably already have protected your MySQL database from SQL injection attacks. Let's take an extra step to protect the valuable data your MySQL tables hold. You can prevent users from messing with URL Query Strings by validating validating $_GET data before you execute anything with it.
As defined at php.net, $_GET is "an associative array of variables passed to the current script via the HTTP GET method."
To grasp an idea of what we are trying to do, let's create a PHP file named querystrings.php. We can examine the contents of the $_GET array by using the print_r function. Type the following code in our querystrings.php file
print_r($_GET);
Enter the following on your browser:
http://myhost/path/querystrings.php?name=Leo&location=Texas
Of course, replace "myhost/path" according to your server's settings.
Your browser should display something like this:
Array ( [username] => Leo [location] => Texas )
There is two $_GET variables: $_GET['username'] and $_GET['location']. You could easily echo the data inside each variable. But how about allowing only certain $_GET variable names?
Compile a list of the $_GET variable names you use and make sure only those are processed
Let's say you only use 3 different $_GET variables names throughtout your whole Website. The variables names are pageid, sectionid and articleid. You use those variables to display the pages' content. You don't want any user messing with the URL. So let's restrict what they can input on as the URL.
You could throw the following code at an include file and include it at the top of every page on your Website. Since $_GET is an array, we use a foreach loop to find out the array keys being passed and confirm they are one of the three accepted array keys. If they are not, the user will be redirected to an error page.
foreach($_GET as $key => $value)
{
if($key != 'pageid' and $key != 'sectionid' and $key! = 'articleid')
{
header('location:errorpage.php');
exit();
}
}
What if you have developed a Website or Web application that uses dozens of $_GET variables names? You could create an array or even a MySQL table with the allowed $_GET variable names and use it to validate them.
$allow = array('pageid', 'sectionid', 'articleid');
foreach($_GET as $key => $value)
{
$valid = false;
foreach($allow as $key_allow => $value_allow)
{
if($key==$value_allow)
{
$valid = true;
}
}
if($valid==false)
{
header('location:errorpage.php');
exit();
}
}