Forum Moderators: coopster

Message Too Old, No Replies

Using filter_var(), alternative based on processing speed

         

csdude55

8:08 pm on Jan 4, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm looking at this:

$age = filter_var($age, FILTER_VALIDATE_INT,
['options' =>
[
'default' => 18,
'min_range' => 18,
'max_range' => 99
]
]
);

Then I compared it to this in a speed test:

if (is_int($age)) {
if ($age < 18) $age = 18;
else if ($age > 99) $age = 99;
}
else $age = 18;


In this case, filter_var() is like 17 times slower!

Test 1: 0.0034282207489014
Test 2: 0.0001990795135498

As far as I can tell they have the same result.

Is filter_var() by nature always going to be slower, or am I doing something wrong?

robzilla

9:19 am on Jan 5, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is filter_var() by nature always going to be slower

Simpler = faster. Look up the source code of filter_var and you'll find it's quite a bit more complex than is_int and a few number comparisons.

csdude55

6:36 pm on Jan 5, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In this case I'm sanitizing data from the query string, and just making sure that they're integers and fit my range. There was a period where crackers were trying to send something like age=18;select+*+from+table+blahblahblah. Those didn't go anywhere, of course, and now I look more closely at the query string to block those queries altogether. So this is really just a backup plan in case one of those make it past my blockade.

Do you think that filter_var() is overkill for this purpose?

robzilla

7:02 pm on Jan 5, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Kind of, yes. And the other code is easier to read if you're not intimately familiar with filter_var.

csdude55

7:20 pm on Jan 6, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Based on that, then, I'm trying to write a more universal function to which I can send all variables that are supposed to be an integer.

Thoughts on improvements?

function force_int($val, $default=18, $min=false, $max=false) {
$val = intval($val);

if ($val && is_int($val)) {
if ($min && $val < $min) $val = $min;
else if ($max && $val > $max) $val = $max;
}
else $val = $default;

return $val;
}

// 18
echo force_int("firty");

// 40
echo force_int("40", 18, 18, 99);

// 18
echo force_int(12, 99, 18, 99);