Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing Integer Database Input

Tags:

php

mysql

I have an application that takes data via a POST request. I am using this data to insert a new row into the database. I know that using mysql_real_escape_string() (plus removing % and _) is the way to go for strings, but what about integer values? Right now, I am using the PHP function intval() on them.

However, I wanted to make sure that intval() is perfectly safe. I can't see a way of an attacker preforming a SQL injection attack when the variables are run through intval() first (since it always returns an integer), but I wanted to make sure this is the case from people that have more experience than I.

Thanks.

like image 428
Dan D. Avatar asked Jul 08 '10 21:07

Dan D.


2 Answers

Yes, intval() is safe. There is absolutely no way to perform an SQL injection when the parameter is converted to integer, because (obviously) the format of an integer does not allow putting SQL keywords (or quotes, or whatever) in it.

like image 182
Etienne Dechamps Avatar answered Sep 18 '22 00:09

Etienne Dechamps


The easiest way to prevent SQL injection is to always use prepared statments. Use the mysqli libraries or better yet an ORM such as doctrine etc.

Your queries then become something like:

$stmt = $db->prep_stmt("select * from .... where userid = ? and username = ?");

/* Binding 2 parameters. */
$stmt->bind_param("is", $userid, $username);

$userid = 15;
$username = "don";

/* Executing the statement */
$stmt->execute( ) or die ("Could not execute statement");
like image 35
Byron Whitlock Avatar answered Sep 20 '22 00:09

Byron Whitlock