Well, imo. When it comes to the $_GET parameter, you should be validating to make sure it meets your standards.
Let’s say cat is suppose to be a number, but someone tried passing a letter or even \1
, let’s take it 1 step at a time.
filename: index.php
<?php
if(isset($_GET['cat'])) {
if(is_numeric($_GET['cat'])) {
print($_GET['cat']);
} else {
print('Not a number');
}
} else {
print('$_GET parameter is not set');
}
In the above snippet starting from the first if statement, we check to see if the $_GET parameter exists first, if not. They’re not looking for cat. This could be the home page of index.php.
Next, we check to see if cat is a numeric character.
PLEASE NOTE
is_numeric will only allow numeric characters, however it also allows decimals to be in there for some odd reason. I don’t know why. I’ve tested is_int and is_integer and they both reject a single string integer. Only one that allows integers is is_numeric.
But we only want whole numbers, no problem though. We can do some more validating.
<?php
if(isset($_GET['cat'])) {
if(is_numeric($_GET['cat'])) {
if(strpos($_GET['cat'], '.') === false) {
print($_GET['cat']);
} else {
print('Numeric, but it has a decimal. We only want whole numbers.');
}
} else {
print('Not a number');
}
} else {
print('$_GET parameter is not set');
}
Using the magic touch of strpos, we can define a string or a character in the $_GET parameter to see if that defined string or character exists within the $_GET parameter. In this case, we are just looking for the period so we just need to define that period.
For strpos, === false means false. !== false means true. You can’t do === true or !== true for some reason. It’ll give you a totally different result than what you want.
Then we simply use this layout to determine if the user’s input is a valid number. If it isn’t, give them those custom errors. If it is, you can then set a variable such as the one in the earlier snippet forcing the variable to be an integer. This will make things more easier.