I'm new to PHP and this question seems stupid.
But I'm really confused with the associative array $_GET, which can help me access the all parameters that has been sent via URL.
Suppose I'm expecting a string of product_ID, and write in the code like this :
$id = $_GET['prod_id'];
Get_Data($id);
While Get_Data() is a function that expects the only parameter to be string, but not array. What if some bad guy type in the url something like this :
.../product.php?prod_id[]=1&prod_id[]=2
The method using $_GET['prod_id']
will return an array(1,2) instead of a string. This can lead to some really bad trouble in my application.
Now, the question : Is there a global way to avoid the case above ?
[EDIT]
Sometimes I want to get array from $_GET['prod_id']
instead of string (ex: getting data from a multi-selectbox, where users can pick more than 1 product)
Is it feasible for me to check if the returning array is in correct structure (1 dimensional array, with innocent data) or has been cheated by some bad guy like this :
.../product.php?prod_id[a]=1&prod_id[b]=2&prod_id[c]=3&prod_id[d]=4
I think it's very easy to pass an array with complex structure to php $_GET, but very hard for coder to check if it's the correct structure they needed.
Can you please enlighten me? Thanks !
The answer is: Validation
One usually use the filter_input()
function.
If sometimes you want it to be an array, use a condition if (is_array($_GET['prod_id']))
and use different set of validations.
$id = str($_GET['prod_id']);
That typecasts the variable as a string literal.
If an array was submitted in the URL, then when retrieved via $_GET
, it will be a PHP array rather than a string that looks like a serialized array.
// Inside a form performing a get request:
// [] on a name makes it an array:
<input type='checkbox' name=arr[] value='chk1' />
<input type='checkbox' name=arr[] value='chk2' />
// Dumps an array, rather than a serialized string
print_r($_GET['arr']);
So in your first case:
$id = $_GET['prod_id'];
Get_Data($id);
You should be validating the contents of $id
to be within the bounds you expect, and if you try to use it as a string when it is really an array, the functions acting on it will throw warnings or errors. Since PHP is weakly typed, a function expecting an integer will happily run if you pass it an array, but will likely crash and burn with errors all over your logs or the screen.
// Make sure $id is an int
if (!ctype_digit($id)) {
// invalid data, abort!
}
On the other hand, if the value is expected to be an array:
if (!is_array($_GET['prod_id'])) {
// it wasn't an array, abort!
}
Use validation, something like this:
$id = (!isset($_GET['prod_id'])) ? null : $_GET['prod_id'];
if (intval($id) > 0) {
//...
}
#OR
if (is_int($id) > 0) {
//...
}