Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I using FILTER_VALIDATE_INT + FILTER_SANITIZE_NUMBER_INT correctly?

Tags:

php

mysqli

Trying to validate and then sanitize $_GET requests. I just want to see if I am missing anything.

Here is what I have...

if (isset($_GET['id'])) {
    $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$id) {
           echo 'Error';
           exit();
        }
    $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
    $getinfo = mysqli_query($link, sprintf("SELECT column1, column2 FROM table WHERE id = '%s'", mysqli_real_escape_string($link, $id)));
        $row = mysqli_fetch_assoc($getinfo);
            if (!$row) {
             echo 'Error';
             exit();
            }
    //execute rest of code
}

Also, I know I should be using PDO and I plan on converting everything to that at some point, but I want to know I am doing this the right way using mysqli right now.

I guess I'm somewhat confused too...if I'm using FILTER_VALIDATE_INT first, do I even need to use FILTER_SANITIZE_NUMBER_INT afterwards? I'm already checking whether or not it's purely INT...

edit: edited to add error handling for FILTER_VALIDATE_INT.

like image 901
jotty Avatar asked Mar 18 '23 22:03

jotty


1 Answers

Indeed, you do not need that. You either validate, or you sanitise.

Validation is a binary result, it's either the original value or false.
Sanitisation always gives you a result, but this may or may not have much to do with the original input. It simply guarantees that you're getting what you ask for, and any input will be squeezed into whatever schema you asked for (here, an integer).

It doesn't really make sense to use both techniques together.

like image 152
deceze Avatar answered Apr 28 '23 09:04

deceze