Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Security - (int) vs FILTER_VALIDATE_INT

Tags:

I recently was told there is FILTER_VALIDATE_INT which is great by the way.

My question is in terms of taking an integer value from the website whether it maybe from user or generated from the web application, and passed via query string.

The value (integer) may be displayed or used in mysql query.

I am trying to structure the best possible security method for this.

With that in mind, is it safe to simply use

$myNum = (int)$_GET['num'];

Or

if (filter_var($_GET['num'], FILTER_VALIDATE_INT)) $myNum = $_GET['num'];

Also, please explain what is the difference between using (int) and FILTER_VALIDATE_INT

like image 951
Adil Avatar asked Jan 25 '11 03:01

Adil


1 Answers

The difference is that a cast to int will always get you an int, which may or may not be the original value. E.g. (int)'foobar' results in the int 0. This makes it safe for most SQL purposes, but has nothing to do with the original value, and you won't even know it.

filter_var with FILTER_VALIDATE_INT tells you whether the value is an int, based on which you can make the decision to use it in an SQL query or display an error message to the user.

like image 54
deceze Avatar answered Sep 25 '22 13:09

deceze