We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

sanitize int returns string

I try to sanitize an integer

$myInt = $this->filter->sanitize(34, "int");

var_dump($myInt)

The output is string '34' (length=2). Is this a bug or am I missing something?

As I do this very dynamically in my code I can't add (int)

Best, Thorsten

Why can't you cast it to an int?

$myInt = (int)$this->filter->sanitize(34,"int");

I've an array which handles the sanitization:

$allowedFields = ['firstName' => 'string', 'lastName' => 'string', 'age' => 'int'];

I realy don't get why an integer santization returns a string.



125.8k
Accepted
answer

I don't use sanitization like that, so I had to re-read the docs. The sanitization doesn't ensure the field is of the specified type (ie: it doesn't ensure 34 is an integer), it just removes any characters that aren't allowed in the specified type. So, "34abc" sanitized would return "34". Numbers don't have "characters" per se, so the variable needs to be converted to a string so (presumably) the appropriate regex can be run on it. I believe the built-in (to PHP) filters do the same thing.

You can write your own filters: https://docs.phalcon.io/en/latest/reference/filter.html#creating-your-own-filters. You could write your own that casts to the integer type after sanitization.

Thanks!

Just added:

$di->setShared(
    'filter', function () {
        $filter = new \Phalcon\Filter();

        // Change int filter to return int
        $filter->add(
            'int', function ($value) {
                return (int) filter_var($value, FILTER_VALIDATE_INT);
            }
        );

        return $filter;
    }
);

Good to see. Please accept an answer so this thread gets flagged as "solved"