Page 1 of 1

sql injection prevention

Posted: Fri Jan 02, 2009 3:58 pm
by SidewinderX
PHP converts all GET/POST requests to strings, and almost every "tutorial" I've come across suggests using mysql_real_escape_string as prevention for sql injections. In almost all instances this is fine due to PHP's dynamic typing, but what precautions should I take if I want a request to be handled explicitly as a specific type other than a string? Would casting it to (int), (bool), (double) be secure?

Re: sql injection prevention

Posted: Fri Jan 02, 2009 8:05 pm
by califdon
SidewinderX wrote:PHP converts all GET/POST requests to strings, and almost every "tutorial" I've come across suggests using mysql_real_escape_string as prevention for sql injections. In almost all instances this is fine due to PHP's dynamic typing, but what precautions should I take if I want a request to be handled explicitly as a specific type other than a string? Would casting it to (int), (bool), (double) be secure?
mysql_real_escape_string is not the same as validating data for type or range. Start with defining clearly what you are trying to protect against. You may find this of value: http://www.w3schools.com/PHP/php_filter.asp (pertains to PHP 5 only)

Re: sql injection prevention

Posted: Sat Jan 03, 2009 1:52 pm
by SidewinderX
Thank you califdon. I am trying to reinvent the wheel and emulate mysqli's prepared statements, which allows you to define the type of your inputs - i,s,d, and b (integer, string, float, and blob respectively). Since you can specify the type, I assumed it handled the sanitation differently.

Re: sql injection prevention

Posted: Sat Jan 03, 2009 2:45 pm
by kaisellgren

Code: Select all

(int) $_GET['value'];
Is safe, however, it's best to always escape data you pass into a database.