Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of intval & real_escape_string when sanitizing integers

Tags:

php

mysql

mysqli

dear All.

I'm using integer PKs in some tables of mysql database. Before input from PHP script, I am doing some sanitizing, which includes intval($id) and $mysqli->real_escape_string().

The queries are quite simple

insert into `tblproducts`(`supplier_id`,`description`) values('$supplier_id','$description')

In this example, $description goes through real_escape_string(), while $supplier_id only being intval()'ed.

I'm just curious, if there're any situations, when I need to apply both intval and real_escape_string to integer I'm inserting into DB? So basically do I really need to use?

$supplier_id = intval($mysqli->real_escape_string($supplier_id));

Thank you.

like image 931
paulus Avatar asked Nov 21 '11 01:11

paulus


People also ask

What is the use of Intval?

The intval() function returns the integer value of a variable.

What is int val?

intval — Get the integer value of a variable.

How do I check if a variable is an int in PHP?

The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

What is parseInt in PHP?

The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.


2 Answers

intval way faster than real_escape_string since real_escape_string has to connect to the database and escaping based on the charset/collation.

you can also cast the int like:

$val = (int)$val;

therefore no need to double sanitize

like image 107
Derek Avatar answered Oct 28 '22 03:10

Derek


You do not have to use $mysqli->real_escape_string after running intval on an variable. intval() will return 0 if it is not an integer and if it is a integer it will return the value.

Example:
$variable = '5';
$variable2 = 'c5b';
if(intval($variable)) echo 'It is a variable'; # intval will return 5 or true
if(intval($variable2)) echo 'It is a variable'; # intval will return 0 or false since it has a letter

There is some cases where intval will return the first integer in the string if it is set to '5b'

like image 20
James Williams Avatar answered Oct 28 '22 03:10

James Williams