0

I am building a page where GET parameters are used and i am wondering if this piece of code successfully evaluates the next conditions: $_GET["id"] must be an integrer and $_GET["status"] must be a "true" or "false".

$rawId = $_GET["id"];
$rawStatus = $_GET["status"];

$Id = filter_var($rawId, FILTER_SANITIZE_NUMBER_INT);
$Id = filter_var($Id, FILTER_VALIDATE_INT);

if (!$Id) {
    die();
}

if ($rawStatus != "true" && $rawStatus != "false") {
    die();
}
DeFabregas
  • 49
  • 5

3 Answers3

0

You can use is_int and is_bool to achieve this. Make sure you are also checking if the $_GET vars are set before you do this to avoid potential notices

$rawId = (isset($_GET["id"]) ? $_GET["id"] : null);
$rawStatus = (isset($_GET["status"]) ? $_GET["status"] : null);

if (!is_int($rawId)) {
     //handle
}

if (!is_bool($rawStatus)) {
     //handle
}
Juakali92
  • 1,155
  • 8
  • 20
0

FILTER_SANITIZE_NUMBER_INT allows for ., + and -, which you probably don't want to include. Using FILTER_VALIDATE_INT would be fine for regular integer checks, though keep in mind that this will return false for 0. If you want your IDs to also include 0, then you'll need to explicitly check for this:

$Id = filter_var($rawId, FILTER_VALIDATE_INT) === 0 || filter_var($rawId, FILTER_VALIDATE_INT));

Assuming you want $rawStatus to be a literal string of true / false, then the way you have it covered at the moment is probably the most optimal approach, though it sounds like you're trying to make a boolean check here. In this case, you can simply check for the presence of $rawStatus, using the lack of its presence to denote a falsy value:

if ($rawStatus)

And as you mention in your comment, you will indeed want to check that both are set with isset()... but you'll also want to check that the values are not empty. This can be done with !empty().

I'd also recommend only proceeding in a know valid state, rather than calling die() in a known invalid state.

Putting this all together, you'll have something that looks like the following:

$rawId = null;

if (isset($_GET["id"]) && !empty($_GET["id"])) {
    $rawId = $_GET["id"];
}
if (isset($_GET["status"]) && !empty($_GET["status"])) {
    $rawStatus = $_GET["status"];
}

$Id = filter_var($rawId, FILTER_VALIDATE_INT) === 0 || filter_var($rawId, FILTER_VALIDATE_INT);

if ($Id && $rawStatus) {
    // Logic
}
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

If you need to check the type of $rawId and $rawStatus you can do it

is_integer($rawId); // return true if $rawId is integer
is_bool($rawStatus); // return true if $rawStatus is boolean

To check if $rawId has only numbers you can do it

is_numeric($rawId)

To check if $rawStatus is bool you can see this answer

Test if string could be boolean PHP

If is needed to parse the values you can use intval() and boolval()